I got this error when I made the bonehead mistake of importing MatSnackBar
instead of MatSnackBarModule
in app.module.ts
.
The answer depends a little bit on the version of conda
that you have installed. For versions of conda >= 4.4, it should be enough to deactivate
the conda environment after the initialization, so add
conda deactivate
right underneath
# <<< conda initialize <<<
If you are using angular version 8 please run the below command to fix this issue.
ng update @angular/cli @angular/core
I resolved this by installing Angular on a 64 bit operating system. I was getting the error because I was initially running it on a 32 bit OS
Use this command for Angular 6 to build
ng build --prod --configuration=dev
Android, Python !
When I saw these two keywords together in your question, Kivy is the one which came to my mind first.
Before coming to native Android development in Java using Android Studio, I had tried Kivy. It just awesome. Here are a few advantage I could find out.
Simple to use
With a python basics, you won't have trouble learning it.
Good community
It's well documented and has a great, active community.
Cross platform.
You can develop thing for Android, iOS, Windows, Linux and even Raspberry Pi with this single framework. Open source.
It is a free software
At least few of it's (Cross platform) competitors want you to pay a fee if you want a commercial license.
Accelerated graphics support
Kivy's graphics engine build over OpenGL ES 2 makes it suitable for softwares which require fast graphics rendering such as games.
Now coming into the next part of question, you can't use Android Studio IDE for Kivy. Here is a detailed guide for setting up the development environment.
Adding AngularFirestoreModule.enablePersistence()
in import section resolved my issue:
imports: [
BrowserModule, AngularFireModule,
AngularFireModule.initializeApp(config),
AngularFirestoreModule.enablePersistence()
]
In PostMan we have ->Pre-request Script. Paste the Below snippet.
const dateNow = new Date();
postman.setGlobalVariable("todayDate", dateNow.toLocaleDateString());
And now we are ready to use.
{
"firstName": "SANKAR",
"lastName": "B",
"email": "[email protected]",
"creationDate": "{{todayDate}}"
}
If you are using JPA Entity classes then use the below snippet
@JsonFormat(pattern="MM/dd/yyyy")
@Column(name = "creation_date")
private Date creationDate;
Don't need to use this method:
.map((res: Response) => res.json() );
Just use this simple method instead of the previous method. hopefully you'll get your result:
.map(res => res );
Create multiple appSettings.$(Configuration).json
files like:
appSettings.staging.json
appSettings.production.json
Create a pre-build event on the project which copies the respective file to appSettings.json
:
copy appSettings.$(Configuration).json appSettings.json
Use only appSettings.json
in your Config Builder:
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
The problem is the import of ProjectsListComponent
in your ProjectsModule
. You should not import that, but add it to the export array, if you want to use it outside of your ProjectsModule
.
Other issues are your project routes. You should add these to an exportable variable, otherwise it's not AOT compatible. And you should -never- import the BrowserModule
anywhere else but in your AppModule
. Use the CommonModule
to get access to the *ngIf, *ngFor...etc
directives:
@NgModule({
declarations: [
ProjectsListComponent
],
imports: [
CommonModule,
RouterModule.forChild(ProjectRoutes)
],
exports: [
ProjectsListComponent
]
})
export class ProjectsModule {}
project.routes.ts
export const ProjectRoutes: Routes = [
{ path: 'projects', component: ProjectsListComponent }
]
For me I solved this error just by adding this line inside repository
maven { url 'https://maven.google.com' }
I am using the Asp.Net Core angular template project with an Angular 4 front end and webpack. I had to use '/dist/assets/images/' in front of the image name, and store the image in the assets/images directory in the dist directory. eg:
<img class="img-responsive" src="/dist/assets/images/UnitBadge.jpg">
A probable cause could be that you do not pass the command line parameters into the applications main method. I made the same mistake some weeks ago.
public static final void main(String... args) {
SpringApplication.run(Application.class, args);
}
You could put an application.properties file in your test/resources folder. There you set
spring.profiles.active=test
This is kind of a default test profile while running tests.
This worked for me in windows 10 and latest solution :
1) Go inside that conda environment ( activate your_env_name )
2) conda install -n your_env_name ipykernel
3) python -m ipykernel install --user --name build_central --display-name "your_env_name"
(NOTE : Include the quotes around "your_env_name", in step 3)
you can create and initialize array of any object like this.
hero:Hero[]=[];
Removing node_modules
and running npm install
fixed those errors for me.
Others say: npm rebuild node-sass
or npm audit fix
might help.
Where does pip installations happen in python?
I will give a windows solution which I was facing and took a while to solve.
First of all, in windows (I will be taking Windows as the OS here), if you do pip install <package_name>
, it will be by default installed globally (if you have not activated a virtual enviroment).
Once you activate a virtual enviroment and you are inside it, all pip installations will be inside that virtual enviroment.
pip is installing the said packages but not I cannot use them?
For this pip might be giving you a warning that the pip executables like pip3.exe
, pip.exe
are not on your path variable.
For this you might add this path ( usually - C:\Users\<your_username>\AppData\Roaming\Programs\Python\
) to your enviromental variables.
After this restart your cmd
, and now try to use your installed python package. It should work now.
Here are some thoughts and ideas:
Use ROM more creatively.
Store anything you can in ROM. Instead of calculating things, store look-up tables in ROM. (Make sure your compiler is outputting your look-up tables to the read-only section! Print out memory addresses at runtime to check!) Store your interrupt vector table in ROM. Of course, run some tests to see how reliable your ROM is compared to your RAM.
Use your best RAM for the stack.
SEUs in the stack are probably the most likely source of crashes, because it is where things like index variables, status variables, return addresses, and pointers of various sorts typically live.
Implement timer-tick and watchdog timer routines.
You can run a "sanity check" routine every timer tick, as well as a watchdog routine to handle the system locking up. Your main code could also periodically increment a counter to indicate progress, and the sanity-check routine could ensure this has occurred.
Implement error-correcting-codes in software.
You can add redundancy to your data to be able to detect and/or correct errors. This will add processing time, potentially leaving the processor exposed to radiation for a longer time, thus increasing the chance of errors, so you must consider the trade-off.
Remember the caches.
Check the sizes of your CPU caches. Data that you have accessed or modified recently will probably be within a cache. I believe you can disable at least some of the caches (at a big performance cost); you should try this to see how susceptible the caches are to SEUs. If the caches are hardier than RAM then you could regularly read and re-write critical data to make sure it stays in cache and bring RAM back into line.
Use page-fault handlers cleverly.
If you mark a memory page as not-present, the CPU will issue a page fault when you try to access it. You can create a page-fault handler that does some checking before servicing the read request. (PC operating systems use this to transparently load pages that have been swapped to disk.)
Use assembly language for critical things (which could be everything).
With assembly language, you know what is in registers and what is in RAM; you know what special RAM tables the CPU is using, and you can design things in a roundabout way to keep your risk down.
Use objdump
to actually look at the generated assembly language, and work out how much code each of your routines takes up.
If you are using a big OS like Linux then you are asking for trouble; there is just so much complexity and so many things to go wrong.
Remember it is a game of probabilities.
A commenter said
Every routine you write to catch errors will be subject to failing itself from the same cause.
While this is true, the chances of errors in the (say) 100 bytes of code and data required for a check routine to function correctly is much smaller than the chance of errors elsewhere. If your ROM is pretty reliable and almost all the code/data is actually in ROM then your odds are even better.
Use redundant hardware.
Use 2 or more identical hardware setups with identical code. If the results differ, a reset should be triggered. With 3 or more devices you can use a "voting" system to try to identify which one has been compromised.
Do make sure that you haven't written your unit tests in a .NET Standard 2.0 Class Library. The visualstudio runner does not support running tests in netstandard2.0 class libraries at the time of this writing.
Check here for the Test Runner Compatibility matrix:
You will have to provide a link to your file that is accessible through the browser, that is for instance:
<a href="http://my.domain.com/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">
versus
<a href="C:/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">
If you expose your "Projecten" folder directly to the public, then you may only have to provide the link as such:
<a href="/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">
But beware, that your files can then be indexed by search engines, can be accessed by anybody having this link, etc.
I'm assuming you added $this->middleware('auth');
inside the constructor of your controller to get the authentication working. In your login/register forms, if you are using {!! Form::someElement !!}
, add the following line at the top as well:
{!! csrf_field() !!}
Or if you are using input tags inside your forms, just add the following line after <form>
tag:
<input type="hidden" name="_token" value="{{ csrf_token() }}">
Hope this helps.
As of now, Postman comes with its own "Console." Click the terminal-like icon on the bottom left to open the console. Send a request, and you can inspect the request from within Postman's console.
It is possible to access the variables with process.env.blabla
instead of process.env['blabla']
. I recently made it work and commented on how I did it on an issue on GitHub because I had some problems with cache based on the accepted answer. Here is the issue.
I claimed 3.5gb space in ubuntu AWS through this.
clean docker
docker stop $(docker ps -qa) && docker system prune -af --volumes
build again
docker build .
docker-compose build
docker-compose up
If you use MAMP, you might have to set the socket: unix_socket: /Applications/MAMP/tmp/mysql/mysql.sock
If you just want to disable App Transport Policy for local dev servers then the following solutions work well. It's useful when you're unable, or it's impractical, to set up HTTPS (e.g. when using the Google App Engine dev server).
As others have said though, ATP should definitely not be turned off for production apps.
Copy your Plist file and NSAllowsArbitraryLoads. Use this Plist for debugging.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Alternatively, you can use a single plist file and exclude specific servers. However, it doesn't look like you can exclude IP 4 addresses so you might need to use the server name instead (found in System Preferences -> Sharing, or configured in your local DNS).
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>server.local</key>
<dict/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
On Windows, the default settings are as follow (I never installed Monaco nor Menlo)
{
"editor.fontFamily": "Consolas",
"editor.fontSize": 14,
"editor.lineHeight": 19
}
Settings fontSize to 12 and lineHeight to 16 closely approximate Visual Studio set to Consolas with 10pt size. I could not get an exact match (VS Code font is slightly bolder) but close enough.
For windows Anaconda comes with Anaconda Prompt which is a shortcut to cmd and can be used run conda commands without adding anaconda in PATH variable. Find the location of it, copy and rename the copy (say myenv_prompt). Right click myenv_prompt and select properties in the context menu.
The Target form of Properties window should already be filled with text, something like %windir%\system32\cmd.exe "/K" C:\Users\xxx\AppData\Local\Continuum\Miniconda3\Scripts\activate.bat C:\Users\xxx\AppData\Local\Continuum\Miniconda3\
There are three parts of this command 1)start ...\cmd.exe 2)run ...\acitvate.bat with environment 3)...\Miniconda3\
Change 3rd part to path of the environment (say myenv) you want as default i.e. fill the Target form something like %windir%\system32\cmd.exe "/K" C:\Users\xxx\AppData\Local\Continuum\Miniconda3\Scripts\activate.bat C:\Users\xxx\AppData\Local\Continuum\Miniconda3\envs\myenv
Now myenv_prompt will act as shortcut to start cmd with myenv as the default environment for python. This shortcut you can keep in start menu or pinned in taskbar.
One advantage of this method is that you can create a few shortcuts each having different environment as default environment. Also you can set the default folder by filling Start in form of the Properties window
Hope this helps
PS:It is not required to find Anaconda Prompt and can be done by changing target of any shortcut. But you will require to know path of cmd.exe and activate.bat
It is very simple just look at their names @RequestParam it consist of two parts one is "Request" which means it is going to deal with request and other part is "Param" which itself makes sense it is going to map only the parameters of requests to java objects. Same is the case with @RequestBody it is going to deal with the data that has been arrived with request like if client has send json object or xml with request at that time @requestbody must be used.
In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.
The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.
DECLARE
PROD_ROW_ID VARCHAR (10) := NULL;
VIS_ROW_ID NUMBER;
DSC VARCHAR (512);
BEGIN
SELECT ROW_ID
INTO VIS_ROW_ID
FROM SIEBEL.S_PROD_INT
WHERE PART_NUM = 'S0146404';
BEGIN
SELECT RTRIM (VIS.SERIAL_NUM)
|| ','
|| RTRIM (PLANID.DESC_TEXT)
|| ','
|| CASE
WHEN PLANID.HIGH = 'TEST123'
THEN
CASE
WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
THEN
'Y'
ELSE
'N'
END
ELSE
'N'
END
|| ','
|| 'GB'
|| ','
|| RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
INTO DSC
FROM SIEBEL.S_LST_OF_VAL PLANID
INNER JOIN SIEBEL.S_PROD_INT PROD
ON PROD.PART_NUM = PLANID.VAL
INNER JOIN SIEBEL.S_ASSET NETFLIX
ON PROD.PROD_ID = PROD.ROW_ID
INNER JOIN SIEBEL.S_ASSET VIS
ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
INNER JOIN SIEBEL.S_PROD_INT VISPROD
ON VIS.PROD_ID = VISPROD.ROW_ID
WHERE PLANID.TYPE = 'Test Plan'
AND PLANID.ACTIVE_FLG = 'Y'
AND VISPROD.PART_NUM = VIS_ROW_ID
AND PROD.STATUS_CD = 'Active'
AND VIS.SERIAL_NUM IS NOT NULL;
END;
END;
/
References
http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/
just updated the springboot version to 2.1.3 and it worked of me
Edit!: Please be sure that you should have both Python installed on your computer.
Maybe my answer is late for you but I can help someone who has the same problem!
You don't have to download both Anaconda
.
If you are using Spyder
and Jupyter
in Anaconda environmen and,
If you have already Anaconda 2 type in Terminal:
python3 -m pip install ipykernel
python3 -m ipykernel install --user
If you have already Anaconda 3 then type in terminal:
python2 -m pip install ipykernel
python2 -m ipykernel install --user
Then before use Spyder
you can choose Python environment like below!
Sometimes only you can see root and your new Python environment, so root is your first anaconda environment!
Also this is Jupyter. You can choose python version like this!
I hope it will help.
To start redis with a config file all you need to do is specifiy the config file as an argument:
redis-server /root/config/redis.rb
Instead of using and killing PID's I would suggest creating an init script for your service
I would suggest taking a look at the Installing Redis more properly section of http://redis.io/topics/quickstart. It will walk you through setting up an init script with redis so you can just do something like service redis_server start
and service redis_server stop
to control your server.
I am not sure exactly what distro you are using, that article describes instructions for a Debian based distro. If you are are using a RHEL/Fedora distro let me know, I can provide you with instructions for the last couple of steps, the config file and most of the other steps will be the same.
A update version @Chris Wedgwood
's answer for keeping site-packages
(keeping packages installed)
cd ~/.virtualenv/name_of_broken_venv
mv lib/python2.7/site-packages ./
rm -rf .Python bin lib include
virtualenv .
rm -rf lib/python2.7/site-packages
mv ./site-packages lib/python2.7/
You need a ResourceLink in your META-INF/context.xml
file to make the global resource available to the web application.
<ResourceLink name="jdbc/mydb"
global="jdbc/mydb"
type="javax.sql.DataSource" />
I had the same problem with venv in PyCharm. But It is not big problem! Just do:
If you are using a reverse proxy such as nginx in between, you could define a custom token, such as X-API-Token
.
In nginx you would rewrite it for the upstream proxy (your rest api) to be just auth:
proxy_set_header Authorization $http_x_api_token;
... while nginx can use the original Authorization header to check HTTP AUth.
This will work if your route looks like this: localhost:8888/p?tagid=1234
var tagId = req.query.tagid;
console.log(tagId); // outputs: 1234
console.log(req.query.tagid); // outputs: 1234
Otherwise use the following code if your route looks like this: localhost:8888/p/1234
var tagId = req.params.tagid;
console.log(tagId); // outputs: 1234
console.log(req.params.tagid); // outputs: 1234
not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
The native lib is expected in one of the following locations
/usr/java/packages/lib/amd64
/usr/lib64
/lib64
/lib
/usr/lib
and not in
tomcat/lib
The files in tomcat/lib
are all jar
file and are added by tomcat to the classpath
so that they are available to your application.
The native lib is needed by tomcat to perform better on the platform it is installed on and thus cannot be a jar
, for linux it could be a .so
file, for windows it could be a .dll
file.
Just download the native library for your platform and place it in the one of the locations tomcat is expecting it to be.
Note that you are not required to have this lib for development/test purposes. Tomcat runs just fine without it.
org.apache.catalina.startup.Catalina start INFO: Server startup in 2882 ms
EDIT
The output you are getting is very normal, it's just some logging outputs from tomcat, the line right above indicates that the server correctly started and is ready for operating.
If you are troubling with running your servlet then after the run on sever
command eclipse opens a browser window (embeded (default) or external, depends on your config). If nothing shows on the browser, then check the url bar of the browser to see whether your servlet was requested or not.
It should be something like that
http://localhost:8080/<your-context-name>/<your-servlet-name>
EDIT 2
Try to call your servlet using the following url
http://localhost:8080/com.filecounter/FileCounter
Also each web project has a web.xml, you can find it in your project under WebContent\WEB-INF
.
It is better to configure your servlets there using servlet-name
servlet-class
and url-mapping
. It could look like that:
<servlet>
<description></description>
<display-name>File counter - My first servlet</display-name>
<servlet-name>file_counter</servlet-name>
<servlet-class>com.filecounter.FileCounter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>file_counter</servlet-name>
<url-pattern>/FileFounter</url-pattern>
</servlet-mapping>
In eclipse dynamic web project the default context name is the same as your project name.
http://localhost:8080/<your-context-name>/FileCounter
will work too.
conda env export
lists all conda and pip packages in an environment. conda-env
must be installed in the conda root (conda install -c conda conda-env
).
To write an environment.yml
file describing the current environment:
conda env export > environment.yml
References:
You don't have to use Tomcat installation as a server location. It is much easier just to copy the files in the ROOT folder.
Eclipse forgets to copy the default apps (ROOT, examples, etc.) when it creates a Tomcat folder inside the Eclipse workspace. Go to
C:\apache-tomcat-7.0.8\webapps
, R-click on the ROOT folder and copy it. Then go to your Eclipse workspace, go to the.metadata
folder, and search for "wtpwebapps". You should find something likeyour-eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
(or../tmp1/wtpwebapps
if you already had another server registered in Eclipse). Go to thewtpwebapps
folder, R-click, and paste ROOT (say "yes" if asked if you want to merge/replace folders/files). Then reloadhttp://localhost/
to see the Tomcat welcome page.
Source: HTTP Status 404 error in tomcat
To achieve that, I suggest you to use AngularJS Environment Plugin: https://www.npmjs.com/package/angular-environment
Here's an example:
angular.module('yourApp', ['environment']).
config(function(envServiceProvider) {
// set the domains and variables for each environment
envServiceProvider.config({
domains: {
development: ['localhost', 'dev.local'],
production: ['acme.com', 'acme.net', 'acme.org']
// anotherStage: ['domain1', 'domain2'],
// anotherStage: ['domain1', 'domain2']
},
vars: {
development: {
apiUrl: '//localhost/api',
staticUrl: '//localhost/static'
// antoherCustomVar: 'lorem',
// antoherCustomVar: 'ipsum'
},
production: {
apiUrl: '//api.acme.com/v2',
staticUrl: '//static.acme.com'
// antoherCustomVar: 'lorem',
// antoherCustomVar: 'ipsum'
}
// anotherStage: {
// customVar: 'lorem',
// customVar: 'ipsum'
// }
}
});
// run the environment check, so the comprobation is made
// before controllers and services are built
envServiceProvider.check();
});
And then, you can call the variables from your controllers such as this:
envService.read('apiUrl');
Hope it helps.
Tomcat usually does not add classes in src/test/java
to the classpath. They are missing if you run tomcat in scope test. To order tomcat to respect classes in test, use -Dmaven.tomcat.useTestClasspath=true
or add
<properties>
<maven.tomcat.useTestClasspath>true</maven.tomcat.useTestClasspath>
</properties>
To your pom.xml
.
For +300k concurrent connection:
Set these variables in /etc/sysctl.conf
:
fs.file-max = 10000000
fs.nr_open = 10000000
Also, change these variables in /etc/security/limits.conf
:
* soft nofile 10000000
* hard nofile 10000000
root soft nofile 10000000
root hard nofile 10000000
And finally, increase TCP buffers in /etc/sysctl.conf
, too:
net.ipv4.tcp_mem = 786432 1697152 1945728
net.ipv4.tcp_rmem = 4096 4096 16777216
net.ipv4.tcp_wmem = 4096 4096 16777216
for more information please refer to this.
To view the EntityValidationErrors
collection, add the following Watch expression to the Watch window.
((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors
I'm using visual studio 2013
It's best to use miske's answer.
If you really want to use natecarlson's repository, the instructions just below can do any of the following:
apt-get update
gives a 404
error after add-apt-repository
apt-get update
gives a NO_PUBKEY
error after manually adding it to /etc/apt/sources.list
Open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
export GOOD_RELEASE='precise'
export BAD_RELEASE="`lsb_release -cs`"
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-add-repository -y ppa:natecarlson/maven3
mv natecarlson-maven3-${BAD_RELEASE}.list natecarlson-maven3-${GOOD_RELEASE}.list
sed -i "s/${BAD_RELEASE}/${GOOD_RELEASE}/" natecarlson-maven3-${GOOD_RELEASE}.list
apt-get update
exit
echo Done!
If you installed natecarlson's repository (either using add-apt-repository
or manually added to /etc/apt/sources.list
) and you don't want it anymore, open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-get update
exit
echo Done!
I fixed this issue as adding Dynamic Web Module to Project Facets
Use a virtual environment:
$ virtualenv myenv
.. some output ..
$ source myenv/bin/activate
(myenv) $ pip install what-i-want
You only use sudo
or elevated permissions when you want to install stuff for the global, system-wide Python installation.
It is best to use a virtual environment which isolates packages for you. That way you can play around without polluting the global python install.
As a bonus, virtualenv does not need elevated permissions.
The best tool for doing layouts using grid, IMHO, is graph paper and a pencil. I know you're asking for some type of program, but it really does work. I've been doing Tk programming for a couple of decades so layout comes quite easily for me, yet I still break out graph paper when I have a complex GUI.
Another thing to think about is this: The real power of Tkinter geometry managers comes from using them together*. If you set out to use only grid, or only pack, you're doing it wrong. Instead, design your GUI on paper first, then look for patterns that are best solved by one or the other. Pack is the right choice for certain types of layouts, and grid is the right choice for others. For a very small set of problems, place is the right choice. Don't limit your thinking to using only one of the geometry managers.
* The only caveat to using both geometry managers is that you should only use one per container (a container can be any widget, but typically it will be a frame).
Can I recommend doing it this way, define your test like this:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
TestPreperationExecutionListener.class
})
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration
public class TestContext {
@Test
public void testContext(){
}
@Configuration
@PropertySource("classpath:/myprops.properties")
@ImportResource({"classpath:context.xml" })
public static class MyContextConfiguration{
}
}
with the following content in myprops.properties file:
spring.profiles.active=localtest
With this your second properties file should get resolved:
META-INF/spring/config_${spring.profiles.active}.properties
I met this error and tried several ways you guys mentioned still didn't work. I even tried to reinstall Tomcat, still have this error.
The last thing I did was to remove the entire Netbeans and Tomcat. It finally worked out. I know this isn't a good way to solve problem, but if you are really hurry and don't know what to do.
I fixed this issue, this way:
Most of the times it should not be used as the primary key for a table because it really hit the performance of the database. useful links regarding GUID impact on performance and as a primary key.
Another valuable option would be https://github.com/ThomasMcDonald/Localhost-uri-Redirector. It's a very simple html page that redirects to whatever host and port you configure in the UI.
The page is hosted on Github https://thomasmcdonald.github.io/Localhost-uri-Redirector, so you can use that as your OAuth2 redirect url and configure you target host and port in the UI and it will just redirect to your app
I have seen this exception while tomcat started and it almost took many hours to figure out the reason. Finally I found out that there were some Spring JARs of a lower version in the lib folder in addition to the Spring jars in the Maven dependencies. The JARs in the lib were automatically added by Eclipse when I added a new Spring Rest controller. I removed those from the lib folder and then let Maven handle the JARs/dependancies and it was fine. Bottom line is if the JARS managed by maven and jars in the WEB-INF/lib causes a classpath issues, you may encounter this error.
I think it comes from this line in your XML file:
<context:component-scan base-package="org.assessme.com.controller." />
Replace it by:
<context:component-scan base-package="org.assessme.com." />
It is because your Autowired service is not scanned by Spring since it is not in the right package.
I had this problem as well on an OSX machine. I discovered that rails was not installed... which surprised me as I thought OSX always came with Rails. To install rails
sudo gem install rails
sudo gem install jekyll bundler
cd ~/Sites
jekyll new <foldername>
cd <foldername>
OR cd !$
(that is magic ;)bundle install
bundle exec jekyll serve
If you are on windows. Open your cmd at right folder then first
set node_env={your env name here}
hit enter then you can start your node with
node app.js
it will start with your env setting
On Mac OS X:
$ brew install tomcat-native
==> tomcat-native
In order for tomcat's APR lifecycle listener to find this library, you'll
need to add it to java.library.path. This can be done by adding this line
to $CATALINA_HOME/bin/setenv.sh
CATALINA_OPTS="$CATALINA_OPTS -Djava.library.path=/usr/local/opt/tomcat-native/lib"
If $CATALINA_HOME/bin/setenv.sh doesn't exist, create it and make it executable.
Then add it to the eclipse's tomcat arguments (double-click Server > Open Launch Configuration > Arguments tab > VM arguments)
-Djava.library.path=/usr/local/opt/tomcat-native/lib
How about doing this in a much more elegant way with nodejs-config module.
This module is able to set configuration environment based on your computer's name. After that when you request a configuration you will get environment specific value.
For example lets assume your have two development machines named pc1 and pc2 and a production machine named pc3. When ever you request configuration values in your code in pc1 or pc2 you must get "development" environment configuration and in pc3 you must get "production" environment configuration. This can be achieved like this:
Now create new config instance with following syntax.
var config = require('nodejs-config')(
__dirname, // an absolute path to your applications 'config' directory
{
development: ["pc1", "pc2"],
production: ["pc3"],
}
);
Now you can get any configuration value without worrying about the environment like this:
config.get('app').configurationKey;
It's possible to decide which reactor projects to build by specifying the -pl
command line argument:
$ mvn --help
[...]
-pl,--projects <arg> Build specified reactor projects
instead of all projects
[...]
It accepts a comma separated list of parameters in one of the following forms:
[groupId]:artifactId
Thus, given the following structure:
project-root [com.mycorp:parent]
|
+ --- server [com.mycorp:server]
| |
| + --- orm [com.mycorp.server:orm]
|
+ --- client [com.mycorp:client]
You can specify the following command line:
mvn -pl .,server,:client,com.mycorp.server:orm clean install
to build everything. Remove elements in the list to build only the modules you please.
EDIT: as blackbuild pointed out, as of Maven 3.2.1 you have a new -el
flag that excludes projects from the reactor, similarly to what -pl
does:
On heroku server (readonly filesystem), If you want runtime compilation of css (its not recommended but you can do it), make sure you have done settings like below -
# inside config/application.rb
config.assets.enabled = true
config.assets.prefix = Rails.root.join('tmp/assets').to_s
# If you are using sass then keep gem outside of asset group
gem 'sass-rails', '3.1.4'
# inside config/environments/production.rb
config.assets.compile = true
you need to add jar file in your build path..
commons-dbcp-1.1-RC2.jar
or any version of that..!!!!
ADDED : also make sure you have commons-pool-1.1.jar too in your build path.
ADDED: sorry saw complete list of jar late... may be version clashes might be there.. better check out..!!! just an assumption.
Got the same error when using curl on https site like
curl https://api.dis...
as pointed out by ganesh, it was because my version of curl wasn't ssl enabled. went back and downloaded the version with ssl and it worked fine.
Issue:
.Net application code aborts before it starts its execution [Console application or Windows application]
Error received: Aborted with Error code "E0434352"
Exception: Unknown exception
Scenario 1:
When an application is already executed, which have used some of the dependent resources and those resources are still in use with the application executed, when another application or the same exe is triggered from some other source then one of the app throws the error
Scenario 2:
When an application is triggered by scheduler or automatic jobs, it may be in execution state at background, meanwhile when you try to trigger the same application again, the error may be triggered.
Solution:
Create an application, when & where the application release all its resources as soon as completed Kill all the background process once the application is closed Check and avoid executing the application from multiple sources like Batch Process, Task Scheduler and external tools at same time. Check for the Application and resource dependencies and clean up the code if needed.
Cappuccino or PhoneGap.
Sometimes though trying to find a shortcut does not save you time or give you a comparable end product.
I think it's a great way to do it. Not limited to express but I've seen quite a number of node.js projects on github doing the same thing. They take out the configuration parameters + smaller modules (in some cases every URI) are factored in separate files.
I would recommend going through express-specific projects on github to get an idea. IMO the way you are doing is correct.
You have a bad package name
org.apache.log4j.rolling.RollingFileAppender
The correct one is:
org.apache.log4j.RollingFileAppender
on Windows I have python 3.7 installed and I still couldn't activate virtualenv
from Gitbash with ./Scripts/activate
although it worked from Powershell after running Set-ExecutionPolicy Unrestricted
in Powershell and changing the setting to "Yes To All".
I don't like Powershell and I like to use Gitbash, so to activate virtualenv
in Gitbash first navigate to your project folder, use ls
to list the contents of the folder and be sure you see "Scripts". Change directory to "Scripts" using cd Scripts
, once you're in the "Scripts" path use . activate
to activate virtualenv
. Don't forget the space after the dot.
1. Install compilers
#sudo apt-get install make
#sudo apt-get install gcc
2. Install openssl and development libraries
#sudo apt-get install openssl
#sudo apt-get install libssl-dev
3. Install the APR package (Downloaded from http://apr.apache.org/)
#tar -xzf apr-1.4.6.tar.gz
#cd apr-1.4.6/
#sudo ./configure
#sudo make
#sudo make install
You should see the compiled file as
/usr/local/apr/lib/libapr-1.a
4. Download, compile and install Tomcat Native sourse package
tomcat-native-1.1.27-src.tar.gz
Extract the archive into some folder
#tar -xzf tomcat-native-1.1.27-src.tar.gz
#cd tomcat-native-1.1.27-src/jni/native
#JAVA_HOME=/usr/lib/jvm/jdk1.7.0_21/
#sudo ./configure --with-apr=/usr/local/apr --with-java-home=$JAVA_HOME
#sudo make
#sudo make install
Now I have compiled Tomcat Native library in /usr/local/apr/libtcnative-1.so.0.1.27 and symbolic link file /usr/local/apr/@libtcnative-1.so pointed to the library
5. Create or edit the $CATALINA_HOME/bin/setenv.sh file with following lines :
export LD_LIBRARY_PATH='$LD_LIBRARY_PATH:/usr/local/apr/lib'
6. Restart tomcat and see the desired result:
You can't compare two Integer
with a simple ==
they're objects so most of the time references won't be the same.
There is a trick, with Integer
between -128 and 127, references will be the same as autoboxing uses Integer.valueOf()
which caches small integers.
If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.
Resources :
On the same topic :
That's generally controlled by the profile associated with the user Tomcat is connecting as.
SQL> SELECT PROFILE, LIMIT FROM DBA_PROFILES WHERE RESOURCE_NAME = 'IDLE_TIME';
PROFILE LIMIT
------------------------------ ----------------------------------------
DEFAULT UNLIMITED
SQL> SELECT PROFILE FROM DBA_USERS WHERE USERNAME = USER;
PROFILE
------------------------------
DEFAULT
So the user I'm connected to has unlimited idle time - no time out.
You can also download MySql workbench (31Mo) which includes mysql.exe
and mysqldump.exe
.
I successfully tested this when i had to run Perl scripts using DBD:MySql
module to run SQL statements against a distant MySql db.
I have created another alternative to the one posted by Vishal Joshi where the requirement to change the build action to Content is removed and also implemented basic support for ClickOnce deployment. I say basic, because I didn't test it thoroughly but it should work in the typical ClickOnce deployment scenario.
The solution consists of a single MSBuild project that once imported to an existent windows application project (*.csproj) extends the build process to contemplate app.config transformation.
You can read a more detailed explanation at Visual Studio App.config XML Transformation and the MSBuild project file can be downloaded from GitHub.
One can access each element of an array separately using the following code:
Object o=...;
if ( o.getClass().isArray() ) {
for(int i=0; i<Array.getLength(o); i++){
System.out.println(Array.get(o, i));
}
}
Notice that it is unnecessary to know what kind of underlying array it is, as this will work for any array.
Couple of things you can do, without executing the actual report just run the sproc from within the data tab of reporting services. Does it still take time? Another option is to use SQL Profiler and determine what is coming in and out of the database system.
Another thing you can do to test it, so to recreate a simple report without any parameters. Run the report and see if it makes a difference. It could be that your RS report is corrupted or badly formed that may cause the rendering to be really slow.
You can change the port number:
Open the server tab in eclipse -> right click open click on open---->you can change the port number.
Run the application with http://localhost:8080/Applicationname
it will give output and also check http://localhost:8080/Applicationname/index.jsp
I found the better control would be using scalefnt package:
\usepackage{scalefnt}
...
{\scalefont{0.5}
\begin{tikzpicture}
...
\end{tikzpicture}
}
this worked for me
In the Server's tab in Eclipse, Stop the Tomcat server
Right-click the server and select "Clean..."
Right-click the server again and select "Clean Tomcat Work Directory..."
In the Eclipse, select the top-level menu option, Project > Clean ...
Be sure your project is selected and click Ok
Restart Eclipse
nor does it appear in the list of environments that can be added when I click the "Add" button. All I see is the J2EE Runtime Library.
Go get "Eclipse for Java EE developers". Note the extra "EE". This includes among others the Web Tools Platform with among others a lot of server plugins with among others the one for Apache Tomcat 5.x. It's also logically; JSP/Servlet is part of the Java EE API.
Have you tried jQuery.contents() ?
If you don't want execute assembly goal on package, you can use next command:
mvn package assembly:single
Here package is keyword.
Read the InputStream of a file and write it to ServletOutputStream
for sending binary data to the client.
@WebServlet("/files/URLStream")
public class URLStream extends HttpServlet {
private static final long serialVersionUID = 1L;
public URLStream() {
super();
}
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
File source = new File("D:\\SVN_Commit.PNG");
long start = System.nanoTime();
InputStream image = new FileInputStream(source);
/*String fileID = request.getParameter("id");
System.out.println("Requested File ID : "+fileID);
// Mongo DB GridFS - https://stackoverflow.com/a/33544285/5081877
image = outputImageFile.getInputStream();*/
if( image != null ) {
BufferedInputStream bin = null;
BufferedOutputStream bout = null;
ServletOutputStream sos = response.getOutputStream();
try {
bin = new BufferedInputStream( image );
bout = new BufferedOutputStream( sos );
int ch =0; ;
while((ch=bin.read())!=-1) {
bout.write(ch);
}
} finally {
bin.close();
image.close();
bout.close();
sos.close();
}
} else {
PrintWriter writer = response.getWriter();
writer.append("Something went wrong with your request.");
System.out.println("Image not available.");
}
System.out.println("Time taken by Stream Copy = "+(System.nanoTime()-start));
}
}
Result the URL directly to the src
attibute.
<img src='http://172.0.0.1:8080/ServletApp/files/URLStream?id=5a575be200c117cc2500003b' alt="mongodb File"/>
<img src='http://172.0.0.1:8080/ServletApp/files/URLStream' alt="local file"/>
<video controls="controls" src="http://172.0.0.1:8080/ServletApp/files/URLStream"></video>
I would prefer using JConsole for application monitoring, and it does have graphical view. If you’re using JDK 5.0 or above then it’s the best. Please refer to this using jconsole page for more details.
I have been primarily using it for GC tuning and finding bottlenecks.
Unless there is a reason that you want to keep that private/public key pair (id_rsa/id_rsa.pub), or enjoy banging your head on the wall, I'd recommend just recreating them and updating your public key on github.
Start by making a backup copy of your ~/.ssh directory.
Enter the following and respond "y" to whether you want to over write the existing files.
ssh-keygen -t rsa
Copy the contents of the public key to your clipboard. (Below is how you should do it on a Mac).
cat ~/.ssh/id_rsa.pub | pbcopy
Go to your account on github and add this key.
Name: My new public key
Key: <PASTE>
Exit from your terminal and restart a new one.
If you get senseless error messages like "Enter your password" for your public key when you never entered one, consider this start over technique. As you see above, it's not complicated.
Can't find this in actual MSDN documentation, but a moderator in the forums said
I am afraid that OLEDB does not preserve the sheet order as they were in Excel
Excel Sheet Names in Sheet Order
Seems like this would be a common enough requirement that there would be a decent workaround.
As detailed by this answer on this page, a status code of 0 means the request failed for some reason, and a javascript library interpreted the fail as a status code of 0.
1) Use this chrome extension, Requestly to redirect your url from the https
version of your url to the http
version, as this will cause a mixed content security error, and ultimately generate a status code of 0. The advantage of this approach is that you don't have to change your app at all, and you can simply "rewrite" your url using this extension.
2) Change the code of your app to optionally make your endpoint redirect to the http
version of your url instead of the https
version (or vice versa). If you do this, the request will fail with status code 0.
On Linux
cat /proc/<pid>/cmdline
get's you the commandline of the process (including args) but with all whitespaces changed to NUL characters.
If you're writing a bash script, call it by name:
#!/bin/bash
/bin/sh is not guaranteed to be bash. This caused a ton of broken scripts in Ubuntu some years ago (IIRC).
The source builtin works just fine in bash; but you might as well just use dot like Norman suggested.
Find the path to a process name
#!/bin/bash
# @author Lukas Gottschall
PID=`ps aux | grep precessname | grep -v grep | awk '{ print $2 }'`
PATH=`ls -ald --color=never /proc/$PID/exe | awk '{ print $10 }'`
echo $PATH
To run a command as root, and pass it the password at the command prompt, you could do it as so:
import subprocess
from getpass import getpass
ls = "sudo -S ls -al".split()
cmd = subprocess.run(
ls, stdout=subprocess.PIPE, input=getpass("password: "), encoding="ascii",
)
print(cmd.stdout)
For your example, probably something like this:
import subprocess
from getpass import getpass
restart_apache = "sudo /usr/sbin/apache2ctl restart".split()
proc = subprocess.run(
restart_apache,
stdout=subprocess.PIPE,
input=getpass("password: "),
encoding="ascii",
)
apt-get install tig
While inside a git repo, type 'tig', to view an interactive log, hit 'enter' on any log to see more information about it. h for help, which lists the basic functionality.
"Tig" is "Git" backwards.
One area where I found mmap() to not be an advantage was when reading small files (under 16K). The overhead of page faulting to read the whole file was very high compared with just doing a single read() system call. This is because the kernel can sometimes satisify a read entirely in your time slice, meaning your code doesn't switch away. With a page fault, it seemed more likely that another program would be scheduled, making the file operation have a higher latency.
i had the same problem with my jar the solution
Manifest-Version: 1.0
Sealed: true
Class-Path: . lib/jarX1.jar lib/jarX2.jar lib/jarX3.jar
Main-Class: com.MainClass
select export all outpout folders for checked project
This worked for me :)
There are different types of shells. The SSH command execution shell is a non-interactive shell, whereas your normal shell is either a login shell or an interactive shell. Description follows, from man bash:
A login shell is one whose first character of argument zero is a -, or one started with the --login option. An interactive shell is one started without non-option arguments and without the -c option whose standard input and error are both connected to terminals (as determined by isatty(3)), or one started with the -i option. PS1 is set and $- includes i if bash is interactive, allowing a shell script or a startup file to test this state. The following paragraphs describe how bash executes its startup files. If any of the files exist but cannot be read, bash reports an error. Tildes are expanded in file names as described below under Tilde Expansion in the EXPANSION section. When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behav ior. When a login shell exits, bash reads and executes commands from the file ~/.bash_logout, if it exists. When an interactive shell that is not a login shell is started, bash reads and executes commands from ~/.bashrc, if that file exists. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of ~/.bashrc. When bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. Bash behaves as if the following command were executed: if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi but the value of the PATH variable is not used to search for the file name.
Just a note about difference beetween static and dynamic.
None of above worked for me, so here is how y solved it, my class have only 1 method templated..
.h
class Model
{
template <class T>
void build(T* b, uint32_t number);
};
.cpp
#include "Model.h"
template <class T>
void Model::build(T* b, uint32_t number)
{
//implementation
}
void TemporaryFunction()
{
Model m;
m.build<B1>(new B1(),1);
m.build<B2>(new B2(), 1);
m.build<B3>(new B3(), 1);
}
this avoid linker errors, and no need to call TemporaryFunction at all
Another reason for this error can be the combination of AspectJ <= 1.6.11 with JRE > 6.
See Eclipse Bug 353467 and Kieker ticket 307 for details.
This is especially true when everything works fine on JRE 6 and moving to JRE7 breaks things.
od -a $file
is useful to explore those types of question on Linux (similar to dumphex in the above).
Go to Tools > Options > Advanced "Tab"(?) > Encryption Tab
Click the "Validation" button, and uncheck the checkbox for checking validity
Be advised though that this is pretty unsecure as it leaves you wide open to accept any invalid certificate. I'd only do this if using the browser on an Intranet where the validity of the cert isn't a concern to you, or you aren't concerned in general.
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
To set for x minutes we need to set x minutes in the 1st argument and then the path of your script
For 15 mins
*/15 * * * * /usr/bin/php /mydomain.in/cromail.php > /dev/null 2>&1
I realize this question is a bit dated and since it shows up on Google search for similar issue I thought I will expand a little bit more on top of @CowWarrior's answer. I was looking for somewhat similar solution, and after scouring through countless SO question/answers and Bootstrap documentations the solution was pretty simple. Again, this would be using inbuilt Bootstrap collapse
class to show/hide divs and Bootstrap's "Collapse Event".
What I realized is that it is easy to do it using a Bootstrap Accordion, but most of the time even though the functionality required is "somewhat" similar to an Accordion, it's different in a way that one would want to show hide <div>
based on, lets say, menu buttons on a navbar
. Below is a simple solution to this. The anchor tags (<a>
) could be navbar items and based on a collapse event the corresponding div will replace the existing div. It looks slightly sloppy in CodeSnippet, but it is pretty close to achieving the functionality-
All that the JavaScript does is makes all the other <div>
hide using
$(".main-container.collapse").not($(this)).collapse('hide');
when the loaded <div>
is displayed by checking the Collapse event shown.bs.collapse
. Here's the Bootstrap documentation on Collapse Event.
Note: main-container
is just a custom class.
Here it goes-
$(".main-container.collapse").on('shown.bs.collapse', function () { _x000D_
//when a collapsed div is shown hide all other collapsible divs that are visible_x000D_
$(".main-container.collapse").not($(this)).collapse('hide');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>_x000D_
<a href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</a>_x000D_
_x000D_
<div id="Bar" class="main-container collapse in">_x000D_
This div (#Bar) is shown by default and can toggle_x000D_
</div>_x000D_
<div id="Foo" class="main-container collapse">_x000D_
This div (#Foo) is hidden by default_x000D_
</div>
_x000D_
You can include a legend template in the chart options:
//legendTemplate takes a template as a string, you can populate the template with values from your dataset
var options = {
legendTemplate : '<ul>'
+'<% for (var i=0; i<datasets.length; i++) { %>'
+'<li>'
+'<span style=\"background-color:<%=datasets[i].lineColor%>\"></span>'
+'<% if (datasets[i].label) { %><%= datasets[i].label %><% } %>'
+'</li>'
+'<% } %>'
+'</ul>'
}
//don't forget to pass options in when creating new Chart
var lineChart = new Chart(element).Line(data, options);
//then you just need to generate the legend
var legend = lineChart.generateLegend();
//and append it to your page somewhere
$('#chart').append(legend);
You'll also need to add some basic css to get it looking ok.
if(!System.IO.Directory.Exists(@"c:\mp_upload"))
{
System.IO.Directory.CreateDirectory(@"c:\mp_upload");
}
ngModel usually use for input tags for bind a variable that we can change variable from controller and html page but ngBind use for display a variable in html page and we can change variable just from controller and html just show variable.
I have used following command to connect MySQL Server 8.0 in Windows command prompt.
C:\Program Files\MySQL\MySQL Server 8.0\bin>mysql -u root -p my_db
Enter password: ****
or
C:\Program Files\MySQL\MySQL Server 8.0\bin>mysql -u root -p my_db -h localhost
Enter password: ****
Here my_db is schema name.
I can remove whitespaces with this
while word.contains(" ") //double space
word = word.Replace(" "," "); //replace double space by single space.
word = word.trim(); //to remove single whitespces from start & end.
One line answer:
if val, ok := dict["foo"]; ok {
//do something here
}
if
statements in Go can include both a condition and an initialization statement. The example above uses both:
initializes two variables - val
will receive either the value of "foo" from the map or a "zero value" (in this case the empty string) and ok
will receive a bool that will be set to true
if "foo" was actually present in the map
evaluates ok
, which will be true
if "foo" was in the map
If "foo" is indeed present in the map, the body of the if
statement will be executed and val
will be local to that scope.
I stumble upon this question and it grabbed my interest. The accepted answer is completely correct, but I thought I do provide my findings at JVM byte code level to explain why the OP encounter the ClassCastException
.
I have the code which is pretty much the same as OP's code:
public static <T> T convertInstanceOfObject(Object o) {
try {
return (T) o;
} catch (ClassCastException e) {
return null;
}
}
public static void main(String[] args) {
String k = convertInstanceOfObject(345435.34);
System.out.println(k);
}
and the corresponding byte code is:
public static <T> T convertInstanceOfObject(java.lang.Object);
Code:
0: aload_0
1: areturn
2: astore_1
3: aconst_null
4: areturn
Exception table:
from to target type
0 1 2 Class java/lang/ClassCastException
public static void main(java.lang.String[]);
Code:
0: ldc2_w #3 // double 345435.34d
3: invokestatic #5 // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
6: invokestatic #6 // Method convertInstanceOfObject:(Ljava/lang/Object;)Ljava/lang/Object;
9: checkcast #7 // class java/lang/String
12: astore_1
13: getstatic #8 // Field java/lang/System.out:Ljava/io/PrintStream;
16: aload_1
17: invokevirtual #9 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
20: return
Notice that checkcast
byte code instruction happens in the main method not the convertInstanceOfObject
and convertInstanceOfObject
method does not have any instruction that can throw ClassCastException
. Because the main method does not catch the ClassCastException
hence when you execute the main method you will get a ClassCastException
and not the expectation of printing null
.
Now I modify the code to the accepted answer:
public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
try {
return clazz.cast(o);
} catch (ClassCastException e) {
return null;
}
}
public static void main(String[] args) {
String k = convertInstanceOfObject(345435.34, String.class);
System.out.println(k);
}
The corresponding byte code is:
public static <T> T convertInstanceOfObject(java.lang.Object, java.lang.Class<T>);
Code:
0: aload_1
1: aload_0
2: invokevirtual #2 // Method java/lang/Class.cast:(Ljava/lang/Object;)Ljava/lang/Object;
5: areturn
6: astore_2
7: aconst_null
8: areturn
Exception table:
from to target type
0 5 6 Class java/lang/ClassCastException
public static void main(java.lang.String[]);
Code:
0: ldc2_w #4 // double 345435.34d
3: invokestatic #6 // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
6: ldc #7 // class java/lang/String
8: invokestatic #8 // Method convertInstanceOfObject:(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;
11: checkcast #7 // class java/lang/String
14: astore_1
15: getstatic #9 // Field java/lang/System.out:Ljava/io/PrintStream;
18: aload_1
19: invokevirtual #10 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
22: return
Notice that there is an invokevirtual
instruction in the convertInstanceOfObject
method that calls Class.cast()
method which throws ClassCastException
which will be catch by the catch(ClassCastException e)
bock and return null
; hence, "null" is printed to console without any exception.
Here is yet another way without Invoke-Expression
but with two variables
(command:string and parameters:array). It works fine for me. Assume
7z.exe
is in the system path.
$cmd = '7z.exe'
$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'
& $cmd $prm
If the command is known (7z.exe) and only parameters are variable then this will do
$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'
& 7z.exe $prm
BTW, Invoke-Expression
with one parameter works for me, too, e.g. this works
$cmd = '& 7z.exe a -tzip "c:\temp\with space\test2.zip" "C:\TEMP\with space\changelog"'
Invoke-Expression $cmd
P.S. I usually prefer the way with a parameter array because it is easier to
compose programmatically than to build an expression for Invoke-Expression
.
import vs. include
The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import
statement with an include
statement).
Another area of confusion is how to specify the location or path of the included .xsd
file: An XSD import statement has an optional attribute named schemaLocation
but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.
When you do chose to use an external .xsd
file for your WSDL, the schemaLocation
attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:
WSDL:
xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>
XSD:
<xsd:schema targetNamespace="urn:listing3"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>xmlbeans-maven-plugin</artifactId>
<executions>
<execution>
<id>generate-sources-xmlbeans</id>
<phase>generate-sources</phase>
<goals>
<goal>xmlbeans</goal>
</goals>
</execution>
</executions>
<version>2.3.3</version>
<inherited>true</inherited>
<configuration>
<schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
</configuration>
</plugin>
You can read more on this in this great IBM article. It has typos such as xsd:import
instead of xs:import
but otherwise it's fine.
Let's assume we have an array of objects and you want to check if value of name is defined like this,
let persons = [ {"name" : "test1"},{"name": "test2"}];
if(persons.some(person => person.name == 'test1')) {
... here your code in case person.name is defined and available
}
One of my windows services is logged on as Local System in windows server 2016, and I can find the user.config under C:\Windows\SysWOW64\config\systemprofile\AppData\Local\{your application name}.
I think the easiest way is searching your application name on C drive and then check where is the user.config
You need to dig a bit deeper into the api to do this:
from matplotlib import pyplot as plt
plt.plot(range(5))
plt.xlim(-3, 3)
plt.ylim(-3, 3)
plt.gca().set_aspect('equal', adjustable='box')
plt.draw()
I tried this and it totally works. The code is:
stage.getIcons().add(
new Image(
<yourclassname>.class.getResourceAsStream( "icon.png" )));
icon.png is under the same folder as the source files.
It really depends on what you're trying to accomplish. If you have no else clause then if(!doSomething())
seems fine. However, if you have
if(!doSomething()) {
...
}
else {
// do something else
}
I'd probably reverse that logic to remove the !
operator and make the if
clause slightly more clear.
This question has not enough information to answer. A general solution (depending on your GUI framework): add a mouse event handler that will catch clicks and mouse movements. This will give you your (x, y) coordinates. Next use these coordinates to crop your image.
You can use this to replace the function if it doesn't exist:
<script>
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(elt /*, from*/) {
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++) {
if (from in this && this[from] === elt)
return from;
}
return -1;
};
}
</script>
Probably a little late to post my answer here but still I'll post, it might benefit someone though,
I had faced the same problem,
The main reason being that I created the virtualenv as a "root" user But later was trying to activate it using another user.
chmod won't work as you're not the owner of the file, hence the alternative is to use chown (to change the ownership)
For e.g. :
If you have your virtualenv created at /home/abc/ENV
Then CD to /home/abc
and run the command : chown -Rv [user-to-whom-you want-change-ownership] [folder/filename whose ownership needs to be changed]
In this example the commands would be : chown -Rv abc ENV
After the ownership is successfully changed you can simply run source /ENV/bin/./activate and your should be able to activate the virtualenv correctly.
The following code will set the media stream volume to max:
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
AudioManager.FLAG_SHOW_UI);
I think in this case concat
is what you want:
In [12]:
pd.concat([df,df1], axis=0, ignore_index=True)
Out[12]:
attr_1 attr_2 attr_3 id quantity
0 0 1 NaN 1 20
1 1 1 NaN 2 23
2 1 1 NaN 3 19
3 0 0 NaN 4 19
4 1 NaN 0 5 8
5 0 NaN 1 6 13
6 1 NaN 1 7 20
7 1 NaN 1 8 25
by passing axis=0
here you are stacking the df's on top of each other which I believe is what you want then producing NaN
value where they are absent from their respective dfs.
I had this error in code that looked like this:
int A = 1;
int B = A;
The fix is to change it to this
int A = 1;
#define B A
The compiler assigns a location in memory to a variable. The second is trying a assign a second variable to the same location as the first - which makes no sense. Using the macro preprocessor solves the problem.
In addition to the other options, in at least IntelliJ IDEA 2017 Ultimate, WebStorm 2020.2, and probably a ton of other versions, you can do it in a single shortcut.
Edit preferences, search for Select in Project View
, and under Keymap, view the mapped shortcut or map one of your choice.
On the Mac, Ctrl + Option + L is not already used, and is the same shortcut as Visual Studio for Windows uses natively (Ctrl + Alt + L, so that could be a good choice.
I got it.
If you want to use wshttpbinding, u need to add windows credentials as below.
svc.ClientCredentials.Windows.ClientCredential.UserName = "abc";
svc.ClientCredentials.Windows.ClientCredential.Password = "xxx";
thanks
mapStateToProps
receives the state
and props
and allows you to extract props from the state to pass to the component.
mapDispatchToProps
receives dispatch
and props
and is meant for you to bind action creators to dispatch so when you execute the resulting function the action gets dispatched.
I find this only saves you from having to do dispatch(actionCreator())
within your component thus making it a bit easier to read.
https://github.com/reactjs/react-redux/blob/master/docs/api.md#arguments
Python is not Java, nor C/C++ -- you need to stop thinking that way to really utilize the power of Python.
Python does not have pass-by-value, nor pass-by-reference, but instead uses pass-by-name (or pass-by-object) -- in other words, nearly everything is bound to a name that you can then use (the two obvious exceptions being tuple- and list-indexing).
When you do spam = "green"
, you have bound the name spam
to the string object "green"
; if you then do eggs = spam
you have not copied anything, you have not made reference pointers; you have simply bound another name, eggs
, to the same object ("green"
in this case). If you then bind spam
to something else (spam = 3.14159
) eggs
will still be bound to "green"
.
When a for-loop executes, it takes the name you give it, and binds it in turn to each object in the iterable while running the loop; when you call a function, it takes the names in the function header and binds them to the arguments passed; reassigning a name is actually rebinding a name (it can take a while to absorb this -- it did for me, anyway).
With for-loops utilizing lists, there are two basic ways to assign back to the list:
for i, item in enumerate(some_list):
some_list[i] = process(item)
or
new_list = []
for item in some_list:
new_list.append(process(item))
some_list[:] = new_list
Notice the [:]
on that last some_list
-- it is causing a mutation of some_list
's elements (setting the entire thing to new_list
's elements) instead of rebinding the name some_list
to new_list
. Is this important? It depends! If you have other names besides some_list
bound to the same list object, and you want them to see the updates, then you need to use the slicing method; if you don't, or if you do not want them to see the updates, then rebind -- some_list = new_list
.
For me the best way to do this is:
.container{
position: relative;
}
.element{
position: absolute;
top: 50%;
transform: translateY(-50%);
}
The advantage is not having to make the height explicit
As a further useful solution for those of you on Windows 7 and above - if you use:
C:\Program Files\Java>mklink /D jdk8 jdk1.8.0_25
you get a Symbolic Link
folder that can be adjusted whenever a new JDK comes out.
All you need to do then is set your
netbeans_jdkhome="C:\Program Files\Java\jdk8"
(in both locations for Netbeans 8) and you never have to edit the config again. Just tweak the symlink each time your JDK is updated.
In C, int
, char
, long
, etc. are all integers.
They typically have different memory sizes and thus different ranges as in INT_MIN
to INT_MAX
. char
and arrays of char
are often used to store characters and strings. Integers are stored in many types: int
being the most popular for a balance of speed, size and range.
ASCII is by far the most popular character encoding, but others exist. The ASCII code for an 'A' is 65, 'a' is 97, '\n' is 10, etc. ASCII data is most often stored in a char
variable. If the C environment is using ASCII encoding, the following all store the same value into the integer variable.
int i1 = 'a';
int i2 = 97;
char c1 = 'a';
char c2 = 97;
To convert an int
to a char
, simple assign:
int i3 = 'b';
int i4 = i3;
char c3;
char c4;
c3 = i3;
// To avoid a potential compiler warning, use a cast `char`.
c4 = (char) i4;
This warning comes up because int
typically has a greater range than char
and so some loss-of-information may occur. By using the cast (char)
, the potential loss of info is explicitly directed.
To print the value of an integer:
printf("<%c>\n", c3); // prints <b>
// Printing a `char` as an integer is less common but do-able
printf("<%d>\n", c3); // prints <98>
// Printing an `int` as a character is less common but do-able.
// The value is converted to an `unsigned char` and then printed.
printf("<%c>\n", i3); // prints <b>
printf("<%d>\n", i3); // prints <98>
There are additional issues about printing such as using %hhu
or casting when printing an unsigned char
, but leave that for later. There is a lot to printf()
.
I don't how this works, but it worked.
$post_data = json_decode(json_encode($_POST['request_key']));
I have created a small tool passing the call to any console tool you want to start windowless through to the original file:
https://github.com/Vittel/RunHiddenConsole
After compiling just rename the executable to "<targetExecutableName>w.exe" (append a "w"), and put it next to the original executable. You can then call e.G. powershellw.exe with the usual parameters and it wont pop up a window.
If someone has an idea how to check whether the created process is waiting for input, ill be happy to include your solution :)
Another way is to use this.
String path = "/abc/def/ghfj.doc"
String fileName = StringUtils.substringAfterLast(path, "/");
If you pass null to this method it will return null. If there is no match with separator it will return empty string.
I figured this out by printing the PHP configuration and searching by xml.ini. Notice in the following output how xml is loaded twice (first as 20-xml.ini and then as xml.ini):
$ php -i | grep xml
/etc/php.d/20-simplexml.ini,
/etc/php.d/20-xml.ini,
/etc/php.d/20-xmlwriter.ini,
/etc/php.d/30-xmlreader.ini,
/etc/php.d/xml.ini
xmlrpc_error_number => 0 => 0
xmlrpc_errors => Off => Off
libxml Version => 2.9.1
libxml
mbstring.http_output_conv_mimetypes => ^(text/|application/xhtml\+xml) => ^(text /|application/xhtml\+xml)
xml
libxml2 Version => 2.9.1
xmlreader
xmlwriter
libxslt compiled against libxml Version => 2.9.1
If showing this error for ionic3 project when you upload to iTunes Connect, please check this ANSWER
This is my project error when I try to vilidated.
Finally follow this ANSWER, error solved.
$host
is a variable of the Core module.
$host
This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.
This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.
$http_host
is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER
(ref).
$http_HEADER
The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;
Summarizing:
$http_host
equals always the HTTP_HOST
request header.$host
equals $http_host
, lowercase and without the port number (if present), except when HTTP_HOST
is absent or is an empty value. In that case, $host
equals the value of the server_name
directive of the server which processed the request.Here I found another good option to migrate your MongoDB data to Elasticsearch. A go daemon that syncs mongodb to elasticsearch in realtime. Its the Monstache. Its available at : Monstache
Below the initial setp to configure and use it.
Step 1:
C:\Program Files\MongoDB\Server\4.0\bin>mongod --smallfiles --oplogSize 50 --replSet test
Step 2 :
C:\Program Files\MongoDB\Server\4.0\bin>mongo
C:\Program Files\MongoDB\Server\4.0\bin>mongo
MongoDB shell version v4.0.2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 4.0.2
Server has startup warnings:
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten]
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten]
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** WARNING: This server is bound to localhost.
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** Remote systems will be unable to connect to this server.
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** Start the server with --bind_ip <address> to specify which IP
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** addresses it should serve responses from, or with --bind_ip_all to
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** bind to all interfaces. If this behavior is desired, start the
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten] ** server with --bind_ip 127.0.0.1 to disable this warning.
2019-01-18T16:56:44.931+0530 I CONTROL [initandlisten]
MongoDB Enterprise test:PRIMARY>
Step 3 : Verify the replication.
MongoDB Enterprise test:PRIMARY> rs.status();
{
"set" : "test",
"date" : ISODate("2019-01-18T11:39:00.380Z"),
"myState" : 1,
"term" : NumberLong(2),
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"heartbeatIntervalMillis" : NumberLong(2000),
"optimes" : {
"lastCommittedOpTime" : {
"ts" : Timestamp(1547811537, 1),
"t" : NumberLong(2)
},
"readConcernMajorityOpTime" : {
"ts" : Timestamp(1547811537, 1),
"t" : NumberLong(2)
},
"appliedOpTime" : {
"ts" : Timestamp(1547811537, 1),
"t" : NumberLong(2)
},
"durableOpTime" : {
"ts" : Timestamp(1547811537, 1),
"t" : NumberLong(2)
}
},
"lastStableCheckpointTimestamp" : Timestamp(1547811517, 1),
"members" : [
{
"_id" : 0,
"name" : "localhost:27017",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 736,
"optime" : {
"ts" : Timestamp(1547811537, 1),
"t" : NumberLong(2)
},
"optimeDate" : ISODate("2019-01-18T11:38:57Z"),
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"infoMessage" : "",
"electionTime" : Timestamp(1547810805, 1),
"electionDate" : ISODate("2019-01-18T11:26:45Z"),
"configVersion" : 1,
"self" : true,
"lastHeartbeatMessage" : ""
}
],
"ok" : 1,
"operationTime" : Timestamp(1547811537, 1),
"$clusterTime" : {
"clusterTime" : Timestamp(1547811537, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
}
MongoDB Enterprise test:PRIMARY>
Step 4.
Download the "https://github.com/rwynn/monstache/releases".
Unzip the download and adjust your PATH variable to include the path to the folder for your platform.
GO to cmd and type "monstache -v"
# 4.13.1
Monstache uses the TOML format for its configuration. Configure the file for migration named config.toml
Step 5.
My config.toml -->
mongo-url = "mongodb://127.0.0.1:27017/?replicaSet=test"
elasticsearch-urls = ["http://localhost:9200"]
direct-read-namespaces = [ "admin.users" ]
gzip = true
stats = true
index-stats = true
elasticsearch-max-conns = 4
elasticsearch-max-seconds = 5
elasticsearch-max-bytes = 8000000
dropped-collections = false
dropped-databases = false
resume = true
resume-write-unsafe = true
resume-name = "default"
index-files = false
file-highlighting = false
verbose = true
exit-after-direct-reads = false
index-as-update=true
index-oplog-time=true
Step 6.
D:\15-1-19>monstache -f config.toml
All the above did not work for me (XCode 7.3) so I read Apple reference on how to do, and it is much simpler than described above. According to Apple:
Localized values are not stored in the Info.plist file itself. Instead, you store the values for a particular localization in a strings file with the name InfoPlist.strings. You place this file in the same language-specific project directory that you use to store other resources for the same localization.
Accordingly, I created a string file named InfoPlist.strings and placed it in the xx.lproj folder of the "xx" language (and added it to the project using File->Add Files to ...). That's it. No need for the key "Localized resources can be mixed" = YES, and no need for InfoPlist.strings in base.lproj or en.lproj.
The application uses the Info.plist key-value as the default value if it can not find a key in the language specific file. Thus, I put my English value in the Info.plist file and the translated one in the language specific file, tested and everything works.
In particular, there is no need to localize the InfoPlist.strings (which creates a version of the file in the base.lproj, en.lroj, and xx.lproj), and in my case going that way did not work.
To just get the errors from the ModelState, use this Linq:
var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);
I would prevent loops in general if i can, set approaches are much more efficient:
INSERT INTO tblFoo
SELECT TOP (300) n = ROW_NUMBER()OVER (ORDER BY [object_id])
FROM sys.all_objects ORDER BY n;
You can make an extension of UIImageView.
Swift 2.0
import Foundation
import UIKit
extension UIImageView
{
func makeBlurImage(targetImageView:UIImageView?)
{
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = targetImageView!.bounds
blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] // for supporting device rotation
targetImageView?.addSubview(blurEffectView)
}
}
Usage:
override func viewDidLoad()
{
super.viewDidLoad()
let sampleImageView = UIImageView(frame: CGRectMake(0, 200, 300, 325))
let sampleImage:UIImage = UIImage(named: "ic_120x120")!
sampleImageView.image = sampleImage
//Convert To Blur Image Here
sampleImageView.makeBlurImage(sampleImageView)
self.view.addSubview(sampleImageView)
}
Swift 3 Extension
import Foundation
import UIKit
extension UIImageView
{
func addBlurEffect()
{
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = self.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // for supporting device rotation
self.addSubview(blurEffectView)
}
}
Usage:
yourImageView.addBlurEffect()
Addendum:
extension UIView {
/// Remove UIBlurEffect from UIView
func removeBlurEffect() {
let blurredEffectViews = self.subviews.filter{$0 is UIVisualEffectView}
blurredEffectViews.forEach{ blurView in
blurView.removeFromSuperview()
}
}
Swift 5.0:
import UIKit
extension UIImageView {
func applyBlurEffect() {
let blurEffect = UIBlurEffect(style: .light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(blurEffectView)
}
}
We can make it So simple like below
<input type="number" onkeydown="javascript: return event.keyCode == 69 ? false : true" />
_x000D_
Updated Answer
we can make it even more simple as @88 MPG suggests
<input type="number" onkeydown="return event.keyCode !== 69" />
_x000D_
Interesting little problem. It is a bit tricky, since real numbers, not always represent exact integers, even if they are meant to, so it's important to allow a tolerance.
For instance tolerance could be 1E-6, in the unit tests, I kept a rather coarse tolerance to have shorter numbers.
None of the answers that I can read now works in this way, so here is my solution:
public boolean isInteger(double n, double tolerance) {
double absN = Math.abs(n);
return Math.abs(absN - Math.round(absN)) <= tolerance;
}
And the unit test, to make sure it works:
@Test
public void checkIsInteger() {
final double TOLERANCE = 1E-2;
assertThat(solver.isInteger(1, TOLERANCE), is(true));
assertThat(solver.isInteger(0.999, TOLERANCE), is(true));
assertThat(solver.isInteger(0.9, TOLERANCE), is(false));
assertThat(solver.isInteger(1.001, TOLERANCE), is(true));
assertThat(solver.isInteger(1.1, TOLERANCE), is(false));
assertThat(solver.isInteger(-1, TOLERANCE), is(true));
assertThat(solver.isInteger(-0.999, TOLERANCE), is(true));
assertThat(solver.isInteger(-0.9, TOLERANCE), is(false));
assertThat(solver.isInteger(-1.001, TOLERANCE), is(true));
assertThat(solver.isInteger(-1.1, TOLERANCE), is(false));
}
all these solutions look like an overkill. Why use my solution?
previousElementSibling
supported from IE9
document.addEventListener
needs a polyfill
previousSibling
might return a text
Please note i have chosen to return the first/last element in case boundaries are broken. In a RL usage, i would prefer it to return a null.
var el = document.getElementById("child1"),_x000D_
children = el.parentNode.children,_x000D_
len = children.length,_x000D_
ind = [].indexOf.call(children, el),_x000D_
nextEl = children[ind === len ? len : ind + 1],_x000D_
prevEl = children[ind === 0 ? 0 : ind - 1];_x000D_
_x000D_
document.write(nextEl.id);_x000D_
document.write("<br/>");_x000D_
document.write(prevEl.id);
_x000D_
<div id="parent">_x000D_
<div id="child1"></div>_x000D_
<div id="child2"></div>_x000D_
</div>
_x000D_
In my opinion, uniqueidentifier
/ GUID is neither a varchar
nor an nvarchar
but a char(36)
. Therefore I use:
CAST(xyz AS char(36))
In addition to posts by @xdumain, I prefer creating data object before ajax call so you can debug it.
var dataObject = JSON.stringify({
'input': $('#myInput').val(),
'name': $('#myName').val(),
});
Now use it in ajax call
$.ajax({
url: "/Home/SaveChart",
type: 'POST',
async: false,
dataType: 'json',
contentType: 'application/json',
data: dataObject,
success: function (data) { },
error: function (xhr) { } )};
You can easily create a Windows Service that runs code on interval using the 'ThreadPool.RegisterWaitForSingleObject' method. It is really slick and quite easy to get set up. This method is a more streamlined approach then to use any of the Timers in the Framework.
Have a look at the link below for more information:
Running a Periodic Process in .NET using a Windows Service:
http://allen-conway-dotnet.blogspot.com/2009/12/running-periodic-process-in-net-using.html
I have a strong feeling that at the root of this "XY problem" the OP wanted just implode()
function.
i had a similar problem, got it to work after adding '' (single quotes) around the json_encode string. Following from my js file:
var myJsVar = <?php echo json_encode($var); ?> ; -------> NOT WORKING
var myJsVar = '<?php echo json_encode($var); ?>' ; -------> WORKING
just thought of posting it in case someone stumbles upon this post like me :)
Given a changed object and an array:
const item = {...}
let items = [{id:2}, {id:3}, {id:4}];
Update the array with the new object by iterating over the array:
items = items.map(x => (x.id === item.id) ? item : x)
Shorter:
$html = preg_replace("/<script.*?\/script>/s", "", $html);
When doing regex things might go wrong, so it's safer to do like this:
$html = preg_replace("/<script.*?\/script>/s", "", $html) ? : $html;
So that when the "accident" happen, we get the original $html instead of empty string.
For simple situations like the exact example in the OP, I agree that Thierry's answer is the best. However, I think it's useful to point out another approach that becomes easier when you're trying to maintain consistent color schemes across multiple data frames that are not all obtained by subsetting a single large data frame. Managing the factors levels in multiple data frames can become tedious if they are being pulled from separate files and not all factor levels appear in each file.
One way to address this is to create a custom manual colour scale as follows:
#Some test data
dat <- data.frame(x=runif(10),y=runif(10),
grp = rep(LETTERS[1:5],each = 2),stringsAsFactors = TRUE)
#Create a custom color scale
library(RColorBrewer)
myColors <- brewer.pal(5,"Set1")
names(myColors) <- levels(dat$grp)
colScale <- scale_colour_manual(name = "grp",values = myColors)
and then add the color scale onto the plot as needed:
#One plot with all the data
p <- ggplot(dat,aes(x,y,colour = grp)) + geom_point()
p1 <- p + colScale
#A second plot with only four of the levels
p2 <- p %+% droplevels(subset(dat[4:10,])) + colScale
The first plot looks like this:
and the second plot looks like this:
This way you don't need to remember or check each data frame to see that they have the appropriate levels.
Answers above are all cool, but they all missed one thing. group executes tasks(blocks) in the thread where it entered when you use dispatch_group_enter
/dispatch_group_leave
.
- (IBAction)buttonAction:(id)sender {
dispatch_queue_t demoQueue = dispatch_queue_create("com.demo.group", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(demoQueue, ^{
dispatch_group_t demoGroup = dispatch_group_create();
for(int i = 0; i < 10; i++) {
dispatch_group_enter(demoGroup);
[self testMethod:i
block:^{
dispatch_group_leave(demoGroup);
}];
}
dispatch_group_notify(demoGroup, dispatch_get_main_queue(), ^{
NSLog(@"All group tasks are done!");
});
});
}
- (void)testMethod:(NSInteger)index block:(void(^)(void))completeBlock {
NSLog(@"Group task started...%ld", index);
NSLog(@"Current thread is %@ thread", [NSThread isMainThread] ? @"main" : @"not main");
[NSThread sleepForTimeInterval:1.f];
if(completeBlock) {
completeBlock();
}
}
this runs in the created concurrent queue demoQueue
. If i dont create any queue, it runs in main thread.
- (IBAction)buttonAction:(id)sender {
dispatch_group_t demoGroup = dispatch_group_create();
for(int i = 0; i < 10; i++) {
dispatch_group_enter(demoGroup);
[self testMethod:i
block:^{
dispatch_group_leave(demoGroup);
}];
}
dispatch_group_notify(demoGroup, dispatch_get_main_queue(), ^{
NSLog(@"All group tasks are done!");
});
}
- (void)testMethod:(NSInteger)index block:(void(^)(void))completeBlock {
NSLog(@"Group task started...%ld", index);
NSLog(@"Current thread is %@ thread", [NSThread isMainThread] ? @"main" : @"not main");
[NSThread sleepForTimeInterval:1.f];
if(completeBlock) {
completeBlock();
}
}
and there's a third way to make tasks executed in another thread:
- (IBAction)buttonAction:(id)sender {
dispatch_queue_t demoQueue = dispatch_queue_create("com.demo.group", DISPATCH_QUEUE_CONCURRENT);
// dispatch_async(demoQueue, ^{
__weak ViewController* weakSelf = self;
dispatch_group_t demoGroup = dispatch_group_create();
for(int i = 0; i < 10; i++) {
dispatch_group_enter(demoGroup);
dispatch_async(demoQueue, ^{
[weakSelf testMethod:i
block:^{
dispatch_group_leave(demoGroup);
}];
});
}
dispatch_group_notify(demoGroup, dispatch_get_main_queue(), ^{
NSLog(@"All group tasks are done!");
});
// });
}
Of course, as mentioned you can use dispatch_group_async
to get what you want.
In the Terminal, type:
$ curl -V
That's a capital V
for the version
My function will check if the user has selected the file or not and you can also check whether you want to allow that file extension or not.
Try this:
<input type="file" name="fileUpload" onchange="validate_fileupload(this.value);"> function validate_fileupload(fileName) { var allowed_extensions = new Array("jpg","png","gif"); var file_extension = fileName.split('.').pop().toLowerCase(); // split function will split the filename by dot(.), and pop function will pop the last element from the array which will give you the extension as well. If there will be no extension then it will return the filename. for(var i = 0; i <= allowed_extensions.length; i++) { if(allowed_extensions[i]==file_extension) { return true; // valid file extension } } return false; }
Here's a concise version that works with class method callbacks and with regular function callbacks. In this example, to show how parameters are handled, the callback function takes two parameters: bool
and int
.
class Caller {
template<class T> void addCallback(T* const object, void(T::* const mf)(bool,int))
{
using namespace std::placeholders;
callbacks_.emplace_back(std::bind(mf, object, _1, _2));
}
void addCallback(void(* const fun)(bool,int))
{
callbacks_.emplace_back(fun);
}
void callCallbacks(bool firstval, int secondval)
{
for (const auto& cb : callbacks_)
cb(firstval, secondval);
}
private:
std::vector<std::function<void(bool,int)>> callbacks_;
}
class Callee {
void MyFunction(bool,int);
}
//then, somewhere in Callee, to add the callback, given a pointer to Caller `ptr`
ptr->addCallback(this, &Callee::MyFunction);
//or to add a call back to a regular function
ptr->addCallback(&MyRegularFunction);
This restricts the C++11-specific code to the addCallback method and private data in class Caller. To me, at least, this minimizes the chance of making mistakes when implementing it.
When your website is served by only one web server, for each client-server pair, a session object is created and remains in the memory of the web server. All the requests from the client go to this web server and update this session object. If some data needs to be stored in the session object over the period of interaction, it is stored in this session object and stays there as long as the session exists.
However, if your website is served by multiple web servers which sit behind a load balancer, the load balancer decides which actual (physical) web-server should each request go to. For example, if there are 3 web servers A, B and C behind the load balancer, it is possible that www.mywebsite.com/index.jsp is served from server A, www.mywebsite.com/login.jsp is served from server B and www.mywebsite.com/accoutdetails.php are served from server C.
Now, if the requests are being served from (physically) 3 different servers, each server has created a session object for you and because these session objects sit on three independent boxes, there's no direct way of one knowing what is there in the session object of the other. In order to synchronize between these server sessions, you may have to write/read the session data into a layer which is common to all - like a DB. Now writing and reading data to/from a db for this use-case may not be a good idea. Now, here comes the role of sticky-session.
If the load balancer is instructed to use sticky sessions, all of your interactions will happen with the same physical server, even though other servers are present. Thus, your session object will be the same throughout your entire interaction with this website.
To summarize, In case of Sticky Sessions, all your requests will be directed to the same physical web server while in case of a non-sticky loadbalancer may choose any webserver to serve your requests.
As an example, you may read about Amazon's Elastic Load Balancer and sticky sessions here : http://aws.typepad.com/aws/2010/04/new-elastic-load-balancing-feature-sticky-sessions.html
On a 64-bit Windows system, the reading of the various environment variables and some Windows Registry keys is redirected to different sources, depending whether the process doing the reading is 32-bit or 64-bit.
The table below lists these data sources:
X = HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion
Y = HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion
Z = HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
READING ENVIRONMENT VARIABLES: Source for 64-bit process Source for 32-bit process
-------------------------------|----------------------------------------|--------------------------------------------------------------
%ProgramFiles% : X\ProgramW6432Dir X\ProgramFilesDir (x86)
%ProgramFiles(x86)% : X\ProgramFilesDir (x86) X\ProgramFilesDir (x86)
%ProgramW6432% : X\ProgramW6432Dir X\ProgramW6432Dir
%CommonProgramFiles% : X\CommonW6432Dir X\CommonFilesDir (x86)
%CommonProgramFiles(x86)% : X\CommonFilesDir (x86) X\CommonFilesDir (x86)
%CommonProgramW6432% : X\CommonW6432Dir X\CommonW6432Dir
%ProgramData% : Z\ProgramData Z\ProgramData
READING REGISTRY VALUES: Source for 64-bit process Source for 32-bit process
-------------------------------|----------------------------------------|--------------------------------------------------------------
X\ProgramFilesDir : X\ProgramFilesDir Y\ProgramFilesDir
X\ProgramFilesDir (x86) : X\ProgramFilesDir (x86) Y\ProgramFilesDir (x86)
X\ProgramFilesPath : X\ProgramFilesPath = %ProgramFiles% Y\ProgramFilesPath = %ProgramFiles(x86)%
X\ProgramW6432Dir : X\ProgramW6432Dir Y\ProgramW6432Dir
X\CommonFilesDir : X\CommonFilesDir Y\CommonFilesDir
X\CommonFilesDir (x86) : X\CommonFilesDir (x86) Y\CommonFilesDir (x86)
X\CommonW6432Dir : X\CommonW6432Dir Y\CommonW6432Dir
So for example, for a 32-bit process, the source of the data for the %ProgramFiles%
and %ProgramFiles(x86)%
environment variables is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86)
.
However, for a 64-bit process, the source of the data for the %ProgramFiles%
environment variable is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramW6432Dir
...and the source of the data for the %ProgramFiles(x86)%
environment variable is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86)
Most default Windows installation put a string like C:\Program Files (x86)
into the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86)
but this (and others) can be changed.
Whatever is entered into these Windows Registry values will be read by Windows Explorer into respective Environment Variables upon login and then copied to any child process that it subsequently spawns.
The registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesPath
is especially noteworthy because most Windows installations put the string %ProgramFiles%
into it, to be read by 64-bit processes. This string refers to the environment variable %ProgramFiles%
which in turn, takes its data from the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramW6432Dir
...unless some program changes the value of this environment variable apriori.
I have written a small utility, which displays these environment variables for 64-bit and 32-bit processes. You can download it here.
The source code for VisualStudio 2017 is included and the compiled 64-bit and 32-bit binary executables are in the directories ..\x64\Release
and ..\x86\Release
, respectively.
This is a proposal for unordered items. This function works with a single loop and with a hash table and collects all items with their id
. If a root node is found, then the object is added to the result array.
function getTree(data, root) {_x000D_
var o = {};_x000D_
data.forEach(function (a) {_x000D_
if (o[a.id] && o[a.id].children) {_x000D_
a.children = o[a.id].children;_x000D_
}_x000D_
o[a.id] = a;_x000D_
o[a.parentId] = o[a.parentId] || {};_x000D_
o[a.parentId].children = o[a.parentId].children || [];_x000D_
o[a.parentId].children.push(a);_x000D_
});_x000D_
return o[root].children;_x000D_
}_x000D_
_x000D_
var data = { People: [{ id: "12", parentId: "0", text: "Man", level: "1", children: null }, { id: "6", parentId: "12", text: "Boy", level: "2", children: null }, { id: "7", parentId: "12", text: "Other", level: "2", children: null }, { id: "9", parentId: "0", text: "Woman", level: "1", children: null }, { id: "11", parentId: "9", text: "Girl", level: "2", children: null }], Animals: [{ id: "5", parentId: "0", text: "Dog", level: "1", children: null }, { id: "8", parentId: "5", text: "Puppy", level: "2", children: null }, { id: "10", parentId: "13", text: "Cat", level: "1", children: null }, { id: "14", parentId: "13", text: "Kitten", level: "2", children: null }] },_x000D_
tree = Object.keys(data).reduce(function (r, k) {_x000D_
r[k] = getTree(data[k], '0');_x000D_
return r;_x000D_
}, {});_x000D_
_x000D_
console.log(tree);
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
You can set the border color in IE however there are some issues.
Argh... I could have sworn you could do this... just tested and realized I wasn't correct. The notes below still apply though.
in IE8 (Beta1 -> RC1) changing the border color or the background color/image causes a de-theming of the control in WindowsXP (the drop arrow and box look like Windows 95)
you still can't style the options within the select control very well because IE doesn't support it. (see bug #291)
There are no unsigned integers in Java. All integers are signed and in big endian.
On the C side the each byte has tne LSB at the start is on the left and the MSB at the end.
It sounds like you are using LSB as Least significant bit, are you? LSB usually stands for least significant byte. Endianness is not bit based but byte based.
To convert from unsigned byte to a Java integer:
int i = (int) b & 0xFF;
To convert from unsigned 32-bit little-endian in byte[] to Java long (from the top of my head, not tested):
long l = (long)b[0] & 0xFF;
l += ((long)b[1] & 0xFF) << 8;
l += ((long)b[2] & 0xFF) << 16;
l += ((long)b[3] & 0xFF) << 24;
It's worth noting, on top of these other answers, that C++20 solves one of the problems that enum class
has: verbosity. Imagining a hypothetical enum class
, Color
.
void foo(Color c)
switch (c) {
case Color::Red: ...;
case Color::Green: ...;
case Color::Blue: ...;
// etc
}
}
This is verbose compared to the plain enum
variation, where the names are in the global scope and therefore don't need to be prefixed with Color::
.
However, in C++20 we can use using enum
to introduce all of the names in an enum to the current scope, solving the problem.
void foo(Color c)
using enum Color;
switch (c) {
case Red: ...;
case Green: ...;
case Blue: ...;
// etc
}
}
So now, there is no reason not to use enum class
.
I was trying things to duplicate the spools you get from sqlplus. I found the following and hope it helps:
Create your sql script file ie:
Please note the echo and serveroutput.
Test_Spool.SQL
Spool 'c:\temp\Test1.txt';
set echo on;
set serveroutput on;
declare
sqlresult varchar2(60);
begin
select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') into sqlresult from dual;
dbms_output.put_line('The date is ' || sqlresult);
end;
/
Spool off;
set serveroutput off;
set echo off;
Run the script from another worksheet:
@TEST_Spool.SQL
My output from the Test1.txt
set serveroutput on
declare
sqlresult varchar2(60);
begin
select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') into sqlresult from dual;
dbms_output.put_line('The date is ' || sqlresult);
end;
anonymous block completed
The date is 2016-04-07 09:21:32
Spool of
By using just jQuery, you cannot avoid a server call.
However, to achieve this result, I'm using Downloadify, which lets me save files without having to make another server call. Doing this reduces server load and makes a good user experience.
To get a proper CSV you just have to take out all the unnecessary tags and put a ',' between the data.
For readers with an angular.json
(not angular-cli.json
) the key correct key is outputPath. I guess the angular configuration changed to angular.json
in Angular 6, so if you are using version 6 or above you most likely have a angular.json
file.
To change the output path you have to change outputPath und the build options.
example angular.json
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"projects": {
"angular-app": {
"projectType": "application",
[...]
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/angular-app",
"index": "src/index.html",
"main": "src/main.ts",
[...]
I could not find any official docs on this (not included in https://angular.io/guide/workspace-config as I would have expected), maybe someone can link an official resource on this.
For ones that looking this solution in React, If you want to use the spread operator inside style, you should use: babel-plugin-transform-object-rest-spread.
Install it by npm module and configure your .babelrc as such:
{
"presets": ["env", "react"],
"plugins": ["transform-object-rest-spread"]
}
Then you can use like...
const sizing = { width: 200, height: 200 }
<div
className="dragon-avatar-image-background"
style={{ backgroundColor: blue, ...sizing }}
/>
More info: https://babeljs.io/docs/en/babel-plugin-transform-object-rest-spread/
Python doesn't have matrices. You can use a list of lists or NumPy
In Windows 10 (Git bash), i had to use this
php -d memory_limit=-1 C:\\composer\\composer.phar install
You need to use brackets when using the fileExists
step in an if
condition or assign the returned value to a variable
Using variable:
def exists = fileExists 'file'
if (exists) {
echo 'Yes'
} else {
echo 'No'
}
Using brackets:
if (fileExists('file')) {
echo 'Yes'
} else {
echo 'No'
}
If access modifier of base class member function is protected OR public, you can do call member function of base class from derived class. Call to the base class non-virtual and virtual member function from derived member function can be made. Please refer the program.
#include<iostream>
using namespace std;
class Parent
{
protected:
virtual void fun(int i)
{
cout<<"Parent::fun functionality write here"<<endl;
}
void fun1(int i)
{
cout<<"Parent::fun1 functionality write here"<<endl;
}
void fun2()
{
cout<<"Parent::fun3 functionality write here"<<endl;
}
};
class Child:public Parent
{
public:
virtual void fun(int i)
{
cout<<"Child::fun partial functionality write here"<<endl;
Parent::fun(++i);
Parent::fun2();
}
void fun1(int i)
{
cout<<"Child::fun1 partial functionality write here"<<endl;
Parent::fun1(++i);
}
};
int main()
{
Child d1;
d1.fun(1);
d1.fun1(2);
return 0;
}
Output:
$ g++ base_function_call_from_derived.cpp
$ ./a.out
Child::fun partial functionality write here
Parent::fun functionality write here
Parent::fun3 functionality write here
Child::fun1 partial functionality write here
Parent::fun1 functionality write here
IOError: [Errno 13] Permission denied: 'juliodantas2015.json'
tells you everything you need to know: though you successfully made your python program executable with your chmod
, python can't open that juliodantas2015.json'
file for writing. You probably don't have the rights to create new files in the folder you're currently in.
Chrome often times tries to do an OPTIONS
call before doing a post. It does this to make sure the CORS headers are in order. It can be problematic if you are not handling the OPTIONS
call in your API controller.
public void Options() { }
It's better if you create a class that has all the query methods, inclusively, in a different package, so instead of typing all the process in every class, you just call the method from that class.
Looking at the AndroidManifest.xml (link), on line 9:
<activity android:screenOrientation="landscape" android:configChanges="orientation|keyboardHidden" android:name="VncCanvasActivity">
This line specifies the screenOrientation
as landscape, but author goes further in overriding any screen orientation changes with configChanges="orientation|keyboardHidden"
. This points to a overridden function in VncCanvasActivity.java.
If you look at VncCanvasActivity, on line 109 is the overrided function:
@Override
public void onConfigurationChanged(Configuration newConfig) {
// ignore orientation/keyboard change
super.onConfigurationChanged(newConfig);
}
The author specifically put a comment to ignore any keyboard or orientation changes.
If you want to change this, you can go back to the AndroidManifest.xml file shown above, and change the line to:
<activity android:screenOrientation="sensor" android:name="VncCanvasActivity">
This should change the program to switch from portrait to landscape when the user rotates the device.
This may work, but might mess up how the GUI looks, depending on how the layout were created. You will have to account for that. Also, depending on how the activities are coded, you may notice that when screen orientation is changed, the values that were filled into any input boxes disappear. This also may have to be handled.
The classical solution is:
expr 5 \* 5
expr
will only work with integer operands. Another nice option is:
echo 5 5\*p | dc
dc
can be made to work with non-integer operands.
The dataset in ss.csv
contains some columns I am interested in:
ss_ = spark.read.csv("ss.csv", header= True,
inferSchema = True)
ss_.columns
['Reporting Area', 'MMWR Year', 'MMWR Week', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Current week', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Current week, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Med', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Med, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Max', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Max, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2018', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2018, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2017', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2017, flag', 'Shiga toxin-producing Escherichia coli, Current week', 'Shiga toxin-producing Escherichia coli, Current week, flag', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Med', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Med, flag', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Max', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Max, flag', 'Shiga toxin-producing Escherichia coli, Cum 2018', 'Shiga toxin-producing Escherichia coli, Cum 2018, flag', 'Shiga toxin-producing Escherichia coli, Cum 2017', 'Shiga toxin-producing Escherichia coli, Cum 2017, flag', 'Shigellosis, Current week', 'Shigellosis, Current week, flag', 'Shigellosis, Previous 52 weeks Med', 'Shigellosis, Previous 52 weeks Med, flag', 'Shigellosis, Previous 52 weeks Max', 'Shigellosis, Previous 52 weeks Max, flag', 'Shigellosis, Cum 2018', 'Shigellosis, Cum 2018, flag', 'Shigellosis, Cum 2017', 'Shigellosis, Cum 2017, flag']
but I only need a few:
columns_lambda = lambda k: k.endswith(', Current week') or k == 'Reporting Area' or k == 'MMWR Year' or k == 'MMWR Week'
The filter returns the list of desired columns, list is evaluated:
sss = filter(columns_lambda, ss_.columns)
to_keep = list(sss)
the list of desired columns is unpacked as arguments to dataframe select function that return dataset containing only columns in the list:
dfss = ss_.select(*to_keep)
dfss.columns
The result:
['Reporting Area',
'MMWR Year',
'MMWR Week',
'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Current week',
'Shiga toxin-producing Escherichia coli, Current week',
'Shigellosis, Current week']
The df.select()
has a complementary pair: http://spark.apache.org/docs/2.4.1/api/python/pyspark.sql.html#pyspark.sql.DataFrame.drop
to drop the list of columns.
You need to use Integer.parseInt(String)
private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getSource()==jTextField2){
int jml = Integer.parseInt(jTextField3.getText());
jTextField1.setText(numberToWord(jml));
}
}
Just to add to the answers, I think the specific reason in this case, in addition to the misplaced no-repeat
, is the space between url
and (
:
background-image: url ('/image/btn.png') no-repeat; /* Won't work */
background-image: url('/image/btn.png'); /* Should work */
The correct version of your script is as follows;
FILE="cat test"
$FILE | \
while read CMD; do
echo $CMD
done
However this kind of indirection --putting your command in a variable named FILE-- is unnecessary. Use one of the solutions already provided. I just wanted to point out your mistake.
Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
Library Seaborn has this built in with function .despine()
.
Just add:
import seaborn as sns
Now create your graph. And add at the end:
sns.despine()
If you look at some of the default parameter values of the function it removes the top and right spine and keeps the bottom and left spine:
sns.despine(top=True, right=True, left=False, bottom=False)
Check out further documentation here: https://seaborn.pydata.org/generated/seaborn.despine.html
try this solution for me its working
public List<ProjectInfo> GetProjectForCombo()
{
using (MyDataContext db = new MyDataContext
(DBHelper.GetConnectionString()))
{
return (from pro in db.Projects
select new { query }.query).ToList();
}
}
Your JAR may contain source and javadoc, in which case you can simply use jar xf my.jar
to extract them.
Otherwise you can use a decompiler as mentioned in adarshr's answer:
Use JD GUI. Open the application, drag and drop your JAR file into it.
Like Andrew said /exclude
parameter of xcopy should be existing file that has list of excludes.
Documentation of xcopy says:
Using /exclude
List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.
Example:
xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt
and list-of-excluded-files.txt
should exist in current folder (otherwise pass full path), with listing of files/folders to exclude - one file/folder per line. In your case that would be:
exclusion.txt
Check screen orientation in runtime.
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
The real question is: whether to use interfaces or base classes. This has been covered before.
In C#, an abstract class (one marked with the keyword "abstract") is simply a class from which you cannot instantiate objects. This serves a different purpose than simply making the distinction between base classes and interfaces.
You can use the CURSOR_STATUS function to determine its state.
IF CURSOR_STATUS('global','myCursor')>=-1
BEGIN
DEALLOCATE myCursor
END
This maybe due to an incorrect table name from where you are fetching the data. Please verify the name of the table you mentioned in asmx file and the table created in database.
If your integer is timestamp in milliseconds use:
SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name
It will format milliseconds to yyyy-mm-dd string.
window.open('http://www.kidzout.com', '_system');
Will work but only if you have the inappbrowser plugin installed. To install, using terminal, browse to the www folder in your project and type:
phonegap plugin add org.apache.cordova.inappbrowser
or
cordova plugin add org.apache.cordova.inappbrowser
Then it your link will open in the browser.
There is no such functionality in jQuery. Use JSON.stringify
or alternatively any jQuery plugin with similar functionality (e.g jquery-json).
Right click your executable, go to Properties > Compatibility and check the 'Run this program as admin' box.
If you want to run it as admin for all users, do the same thing in 'change setting for all users'.
[
{
id : '1',
title: 'sample title',
....
},
{
id : '2',
title: 'sample title',
....
},
...
]
Check Easy code for this output
Gson gson=new GsonBuilder().create();
List<Post> list= Arrays.asList(gson.fromJson(yourResponse.toString,Post[].class));
If you are using the VSCodeVim
extension, you can use the Vim key shortcuts:
Next tab: gt
Prior tab: gT
Numbered tab: nnngt
You're close. This should do the trick:
new {items = new [] {
new {name = "command" , index = "X", optional = "0"},
new {name = "command" , index = "X", optional = "0"}
}}
If your source was an enumerable of some sort, you might want to do this:
new {items = source.Select(item => new
{
name = item.Name, index = item.Index, options = item.Optional
})};
import warnings
warnings.warn("Warning...........Message")
See the python documentation: here
In case you get a compiler error for __attribute__((noinline))
, you can just try:
noinline int func(int arg)
{
....
}
I've used these codes:
HTML:
<a id="delete-button">Delete</a>
jQuery:
<script>
$("#delete-button").click(function(){
if(confirm("Are you sure you want to delete this?")){
$("#delete-button").attr("href", "query.php?ACTION=delete&ID='1'");
}
else{
return false;
}
});
</script>
These codes works for me, but I'm not really sure if this is proper. What do you think?
@last_run_time
is a 9.4. User-Defined Variables and last_run_time datetime
one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.
Try: SELECT last_run_time;
UPDATE
Example:
/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$
CREATE PROCEDURE `sp_test`()
BEGIN
DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
DECLARE last_run_time DATETIME DEFAULT NULL;
DECLARE current_run_time DATETIME DEFAULT NOW();
-- Define the last run time
SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);
-- if there is no last run time found then use yesterday as starting point
IF(last_run_time IS NULL) THEN
SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
END IF;
SELECT last_run_time;
-- Insert variables in table2
INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$
DELIMITER ;
With Ansible 2.x you can use vars:
with tasks.
Template test.j2
:
mkdir -p {{myTemplateVariable}}
Playbook:
- template: src=test.j2 dest=/tmp/File1
vars:
myTemplateVariable: myDirName
- template: src=test.j2 dest=/tmp/File2
vars:
myTemplateVariable: myOtherDir
This will pass different myTemplateVariable
values into test.j2.
You can also use @mock.patch.object
:
Let's say a module my_module.py
uses pandas
to read from a database and we would like to test this module by mocking pd.read_sql_table
method (which takes table_name
as argument).
What you can do is to create (inside your test) a db_mock
method that returns different objects depending on the argument provided:
def db_mock(**kwargs):
if kwargs['table_name'] == 'table_1':
# return some DataFrame
elif kwargs['table_name'] == 'table_2':
# return some other DataFrame
In your test function you then do:
import my_module as my_module_imported
@mock.patch.object(my_module_imported.pd, "read_sql_table", new_callable=lambda: db_mock)
def test_my_module(mock_read_sql_table):
# You can now test any methods from `my_module`, e.g. `foo` and any call this
# method does to `read_sql_table` will be mocked by `db_mock`, e.g.
ret = my_module_imported.foo(table_name='table_1')
# `ret` is some DataFrame returned by `db_mock`
You can do it with plain JavaScript:
alert('123-4-'.substr(0, 4)); // outputs "123-"
This returns the first four characters of your string (adjust 4
to suit your needs).
Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.
In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.
Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.
First, you really need to keep in mind that it's never impossible to reverse-engineer something. Everything is hackable. A smart developer using a smart IDE can already get far enough.
Well, you can find here a list. ProGuard is pretty good. I've used it myself, but only to "minify" Java code.
You asked:
I was looking for a one-liner like:
Ask and ye shall receive. Convert from terrible legacy class Date
to its modern replacement, Instant
.
myJavaUtilDate.toInstant().toString()
2020-05-05T19:46:12.912Z
In Java 8 and later we have the new java.time package built in (Tutorial). Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.
The best solution is to sort your date-time objects rather than strings. But if you must work in strings, read on.
An Instant
represents a moment on the timeline, basically in UTC (see class doc for precise details). The toString
implementation uses the DateTimeFormatter.ISO_INSTANT
format by default. This format includes zero, three, six or nine digits digits as needed to display fraction of a second up to nanosecond precision.
String output = Instant.now().toString(); // Example: '2015-12-03T10:15:30.120Z'
If you must interoperate with the old Date
class, convert to/from java.time via new methods added to the old classes. Example: Date::toInstant
.
myJavaUtilDate.toInstant().toString()
You may want to use an alternate formatter if you need a consistent number of digits in the fractional second or if you need no fractional second.
Another route if you want to truncate fractions of a second is to use ZonedDateTime
instead of Instant
, calling its method to change the fraction to zero.
Note that we must specify a time zone for ZonedDateTime
(thus the name). In our case that means UTC. The subclass of ZoneID
, ZoneOffset
, holds a convenient constant for UTC. If we omit the time zone, the JVM’s current default time zone is implicitly applied.
String output = ZonedDateTime.now( ZoneOffset.UTC ).withNano( 0 ).toString(); // Example: 2015-08-27T19:28:58Z
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
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
UPDATE: The Joda -Time project is now in maintenance mode, with the team advising migration to the java.time classes.
I was looking for a one-liner
Easy if using the Joda-Time 2.3 library. ISO 8601 is the default formatting.
In the code example below, note that I am specifying a time zone rather than depending on the default time zone. In this case, I'm specifying UTC per your question. The Z
on the end, spoken as "Zulu", means no time zone offset from UTC.
// import org.joda.time.*;
String output = new DateTime( DateTimeZone.UTC );
Output…
2013-12-12T18:29:50.588Z
AFAIK you can not remove attribute at runtime, but only change their values (ie: readonly true/false) look here for something similar . As another way of doing what you want without messing with attributes I will go with a ViewModel for your specific action so you can insert all the logic without breaking the logic needed by other controllers. If you try to obtain some sort of wizard (a multi steps form) you can instead serialize the already compiled fields and with TempData bring them along your steps. (for help in serialize deserialize you can use MVC futures)
If all you want to do is remove the changes made in revision 3, you might want to use git revert.
Git revert simply creates a new revision with changes that undo all of the changes in the revision you are reverting.
What this means, is that you retain information about both the unwanted commit, and the commit that removes those changes.
This is probably a lot more friendly if it's at all possible the someone has pulled from your repository in the mean time, since the revert is basically just a standard commit.
Not just tab icons, notification and launcher lives an app. I was confused about the sizes of the other icons used for different situations in the app.
I'm using 32px mdpi (Action Bar icons) dimensions and I cannot say if it would be correct.
i wrote it today in C,compiled with tcc, figured out during preparation of compititive exams several years back. don't know if anyone already have wrote it alredy. it really fast(but you should decide whether it is fast or not). took one or two minuts to findout about 1,00,004 prime numbers between 10 and 1,00,00,000 on i7 processor with average 32% CPU use. as you know, only those can be prime which have last digit either 1,3,7 or 9 and to check if that number is prime or not, you have to divide that number by previously found prime numbers only. so first take group of four number = {1,3,7,9}, test it by dividing by known prime numbers, if reminder is non zero then number is prime, add it to prime number array. then add 10 to group so it becomes {11,13,17,19} and repeat the process.
#include <stdio.h>
int main() {
int nums[4]={1,3,7,9};
int primes[100000];
primes[0]=2;
primes[1]=3;
primes[2]=5;
primes[3]=7;
int found = 4;
int got = 1;
int m=0;
int upto = 1000000;
for(int i=0;i<upto;i++){
//printf("iteration number: %d\n",i);
for(int j=0;j<4;j++){
m = nums[j]+10;
//printf("m = %d\n",m);
nums[j] = m;
got = 1;
for(int k=0;k<found;k++){
//printf("testing with %d\n",primes[k]);
if(m%primes[k]==0){
got = 0;
//printf("%d failed for %d\n",m,primes[k]);
break;
}
}
if(got==1){
//printf("got new prime: %d\n",m);
primes[found]= m;
found++;
}
}
}
printf("found total %d prime numbers between 1 and %d",found,upto*10);
return 0;
}
I needed to explicitly add POST in the CURL command:
curl -X POST http://<user>:<token>@<server>/safeRestart
I also have the SafeRestart Plugin installed, in case that makes a difference.
You may find OpenJDK 6 and 7 binaries for Windows in openjdk-unofficial-builds github project.
Update: OpenJDK 8 and 11 LTS binaries for Windows x86_64 can be found in ojdkbuild github project.
Disclaimer: I've built them myself.
Update (2019): OpenJDK Updates Project Builds for 8 and 11 are available now.
I had this problem and the instructions from a tech at Microsoft fixed it for me:
It is possible with CSS3 :
#myDiv {
-webkit-filter: blur(20px);
-moz-filter: blur(20px);
-o-filter: blur(20px);
-ms-filter: blur(20px);
filter: blur(20px);
opacity: 0.4;
}
Example here => jsfiddle
foreach($objectA as $k => $v) $objectB->$k = $v;
Look at the import maybe you have a cycle dependency, this was in my case the error, using import {} from 'jasmine';
will fix the errors in the console and make the code compilable but not removes the root of devil (in my case the cycle dependency).
puts true ? "true" : "false"
=> "true"
puts false ? "true" : "false"
=> "false"
The onMessageReceived
method is fired only when app is in foreground or the notification payload only contains the data type.
From the Firebase docs
For downstream messaging, FCM provides two types of payload: notification and data.
For notification type, FCM automatically displays the message to end-user devices on behalf of the client app. Notifications have a predefined set of user-visible keys.
For data type, client app is responsible for processing data messages. Data messages have only custom key-value pairs.Use notifications when you want FCM to handle displaying a notification on your client app's behalf. Use data messages when you want your app to handle the display or process the messages on your Android client app, or if you want to send messages to iOS devices when there is a direct FCM connection.
Further down the docs
App behaviour when receiving messages that include both notification and data payloads depends on whether the app is in the background or the foreground—essentially, whether or not it is active at the time of receipt.
When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification.
When in the foreground, your app receives a message object with both payloads available.
If you are using the firebase console to send notifications, the payload will always contain the notification type. You have to use the Firebase API to send the notification with only the data type in the notification payload. That way your app is always notified when a new notification is received and the app can handle the notification payload.
If you want to play notification sound when app is in background using the conventional method, you need to add the sound parameter to the notification payload.
Add quotation marks (" ") around the %INPUT% so it looks like this:
If "%INPUT%" == "y" goto yes
If "%INPUT%" == "n" goto no
If "%INPUT%" == "Y" goto yes
If "%INPUT%" == "N" goto no
UPDATE MyTable SET MyDate = CONVERT(datetime, '2009/07/16 08:28:01', 120)
For a full discussion of CAST and CONVERT, including the different date formatting options, see the MSDN Library Link below:
https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql
(function(){ _x000D_
let a = function(){console.log(this.b)};_x000D_
a.prototype.b = 1;_x000D_
a.__proto__.b = 2;_x000D_
let q = new a();_x000D_
console.log(a.b);_x000D_
console.log(q.b) _x000D_
})()
_x000D_
Try this code to understand
You can also do like this if you're only interested in extracting the "user_id":
String userId =
given().
contentType("application/json").
body(requestBody).
when().
post("/admin").
then().
statusCode(200).
extract().
path("user_id");
In its simplest form it looks like this:
String userId = get("/person").path("person.userId");
Use subprocess.check_output
(new in python 2.7). It will suppress stdout and raise an exception if the command fails. (It actually returns the contents of stdout, so you can use that later in your program if you want.) Example:
import subprocess
try:
subprocess.check_output(['espeak', text])
except subprocess.CalledProcessError:
# Do something
You can also suppress stderr with:
subprocess.check_output(["espeak", text], stderr=subprocess.STDOUT)
For earlier than 2.7, use
import os
import subprocess
with open(os.devnull, 'w') as FNULL:
try:
subprocess._check_call(['espeak', text], stdout=FNULL)
except subprocess.CalledProcessError:
# Do something
Here, you can suppress stderr with
subprocess._check_call(['espeak', text], stdout=FNULL, stderr=FNULL)
I had issues installing Express on Ubuntu:
If for some reason NPM command is missing, test npm command with npm help
. If not there, follow these steps - http://arnolog.net/post/8424207595/installing-node-js-npm-express-mongoose-on-ubuntu
If just the Express command is not working, try:
sudo npm install -g express
This made everything work as I'm used to with Windows7 and OSX.
Hope this helps!
Strings in C are represented as arrays of characters.
char *p = "String";
You are declaring a pointer that points to a string stored some where in your program (modifying this string is undefined behavior) according to the C programming language 2 ed.
char p2[] = "String";
You are declaring an array of char initialized with the string "String" leaving to the compiler the job to count the size of the array.
char p3[5] = "String";
You are declaring an array of size 5 and initializing it with "String". This is an error be cause "String" don't fit in 5 elements.
char p3[7] = "String";
is the correct declaration ('\0' is the terminating character in c strings).
Process text to and from Unicode at the I/O boundaries of your program using open
with the encoding
parameter. Make sure to use the (hopefully documented) encoding of the file being read. The default encoding varies by OS (specifically, locale.getpreferredencoding(False)
is the encoding used), so I recommend always explicitly using the encoding
parameter for portability and clarity (Python 3 syntax below):
with open(filename, 'r', encoding='utf8') as f:
text = f.read()
# process Unicode text
with open(filename, 'w', encoding='utf8') as f:
f.write(text)
If still using Python 2 or for Python 2/3 compatibility, the io
module implements open
with the same semantics as Python 3's open
and exists in both versions:
import io
with io.open(filename, 'r', encoding='utf8') as f:
text = f.read()
# process Unicode text
with io.open(filename, 'w', encoding='utf8') as f:
f.write(text)
I feel obliged to point out that the method using
signal(SIGPIPE, SIG_DFL)
is indeed dangerous (as already suggested by David Bennet in the comments) and in my case led to platform-dependent funny business when combined with multiprocessing.Manager
(because the standard library relies on BrokenPipeError being raised in several places). To make a long and painful story short, this is how I fixed it:
First, you need to catch the IOError
(Python 2) or BrokenPipeError
(Python 3). Depending on your program you can try to exit early at that point or just ignore the exception:
from errno import EPIPE
try:
broken_pipe_exception = BrokenPipeError
except NameError: # Python 2
broken_pipe_exception = IOError
try:
YOUR CODE GOES HERE
except broken_pipe_exception as exc:
if broken_pipe_exception == IOError:
if exc.errno != EPIPE:
raise
However, this isn't enough. Python 3 may still print a message like this:
Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
BrokenPipeError: [Errno 32] Broken pipe
Unfortunately getting rid of that message is not straightforward, but I finally found http://bugs.python.org/issue11380 where Robert Collins suggests this workaround that I turned into a decorator you can wrap your main function with (yes, that's some crazy indentation):
from functools import wraps
from sys import exit, stderr, stdout
from traceback import print_exc
def suppress_broken_pipe_msg(f):
@wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except SystemExit:
raise
except:
print_exc()
exit(1)
finally:
try:
stdout.flush()
finally:
try:
stdout.close()
finally:
try:
stderr.flush()
finally:
stderr.close()
return wrapper
@suppress_broken_pipe_msg
def main():
YOUR CODE GOES HERE
With the new Angular router, you can add a [routerLinkActive]="['your-class-name']"
attribute to all your links:
<a [routerLink]="['/home']" [routerLinkActive]="['is-active']">Home</a>
Or the simplified non-array format if only one class is needed:
<a [routerLink]="['/home']" [routerLinkActive]="'is-active'">Home</a>
Or an even simpler format if only one class is needed:
<a [routerLink]="['/home']" routerLinkActive="is-active">Home</a>
See the poorly documented routerLinkActive
directive for more info. (I mostly figured this out via trial-and-error.)
UPDATE: Better documentation for the routerLinkActive
directive can now be found here. (Thanks to @Victor Hugo Arango A. in the comments below.)
This is quick-and-dirty (and not formally valid HTML5), but it seems to work -- and it is inline as per the question:
<table border='1' style='border-collapse:collapse'>
No further styling of <tr>
/<td>
tags is required (for a basic table grid).
A much easier and resource friendly approach would be.
import UIKit
@IBDesignable
class CircleDrawView: UIView {
@IBInspectable var borderColor: UIColor = UIColor.red;
@IBInspectable var borderSize: CGFloat = 4
override func draw(_ rect: CGRect)
{
layer.borderColor = borderColor.cgColor
layer.borderWidth = borderSize
layer.cornerRadius = self.frame.height/2
}
}
With Border Color
and Border Size
and the default Background
property you can define the appearance of the circle.
Please note, to draw a circle the view's height and width have to be equal in size.
The code is working for Swift >= 4
and Xcode >= 9
.
There is an important technical difference between race conditions and data races. Most answers seem to make the assumption that these terms are equivalent, but they are not.
A data race occurs when 2 instructions access the same memory location, at least one of these accesses is a write and there is no happens before ordering among these accesses. Now what constitutes a happens before ordering is subject to a lot of debate, but in general ulock-lock pairs on the same lock variable and wait-signal pairs on the same condition variable induce a happens-before order.
A race condition is a semantic error. It is a flaw that occurs in the timing or the ordering of events that leads to erroneous program behavior.
Many race conditions can be (and in fact are) caused by data races, but this is not necessary. As a matter of fact, data races and race conditions are neither the necessary, nor the sufficient condition for one another. This blog post also explains the difference very well, with a simple bank transaction example. Here is another simple example that explains the difference.
Now that we nailed down the terminology, let us try to answer the original question.
Given that race conditions are semantic bugs, there is no general way of detecting them. This is because there is no way of having an automated oracle that can distinguish correct vs. incorrect program behavior in the general case. Race detection is an undecidable problem.
On the other hand, data races have a precise definition that does not necessarily relate to correctness, and therefore one can detect them. There are many flavors of data race detectors (static/dynamic data race detection, lockset-based data race detection, happens-before based data race detection, hybrid data race detection). A state of the art dynamic data race detector is ThreadSanitizer which works very well in practice.
Handling data races in general requires some programming discipline to induce happens-before edges between accesses to shared data (either during development, or once they are detected using the above mentioned tools). this can be done through locks, condition variables, semaphores, etc. However, one can also employ different programming paradigms like message passing (instead of shared memory) that avoid data races by construction.
You can find the shortcut in the Edit menu :
Edit > Toggle Block Comment => Shift-Alt-A
One way to fix up your python2 code is:
import sys
if sys.version_info >= (3, 0):
def xrange(*args, **kwargs):
return iter(range(*args, **kwargs))
Creating a local branch from an existing branch (can be master/ develop/ any-other-branch).
git checkout -b branch_name
Push this to remote
git push -u remote_name local_branch_name:remote_branch_name
Here,
If we remove the local and remote branch names, it will have the format
git push -u remote_name branch_name
This will push the local branch to remote and with the same name as the local branch branch_name. The local branch will be tracking the remote branch as well.
Probably is the use of the "on" event that Bootstrap use a lot and was inserted at jQuery 1.7 http://api.jquery.com/on/
Pandas DataFrame columns are Pandas Series when you pull them out, which you can then call x.tolist()
on to turn them into a Python list. Alternatively you cast it with list(x)
.
import pandas as pd
data_dict = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(data_dict)
print(f"DataFrame:\n{df}\n")
print(f"column types:\n{df.dtypes}")
col_one_list = df['one'].tolist()
col_one_arr = df['one'].to_numpy()
print(f"\ncol_one_list:\n{col_one_list}\ntype:{type(col_one_list)}")
print(f"\ncol_one_arr:\n{col_one_arr}\ntype:{type(col_one_arr)}")
Output:
DataFrame:
one two
a 1.0 1
b 2.0 2
c 3.0 3
d NaN 4
column types:
one float64
two int64
dtype: object
col_one_list:
[1.0, 2.0, 3.0, nan]
type:<class 'list'>
col_one_arr:
[ 1. 2. 3. nan]
type:<class 'numpy.ndarray'>
There is indeed a Groovier Way.
if(members){
//Some work
}
does everything if members
is a collection. Null check as well as empty check (Empty collections are coerced to false
). Hail Groovy Truth. :)
Say you were opening a file in your current directory. The command would be:
start %cd%\filename.filetype
I hope I answered your question.
A simpler solution nowadays would be to use your shape as a background and then programmatically change its color via:
view.background.setColorFilter(Color.parseColor("#343434"), PorterDuff.Mode.SRC_ATOP)
See PorterDuff.Mode for the available options.
UPDATE (API 29):
The above method is deprecated since API 29 and replaced by the following:
view.background.colorFilter = BlendModeColorFilter(Color.parseColor("#343434"), BlendMode.SRC_ATOP)
See BlendMode for the available options.
Yes, underscores may be used anywhere in an identifier. I believe the rules are: any of a-z, A-Z, _ in the first character and those +0-9 for the following characters.
Underscore prefixes are common in C code -- a single underscore means "private", and double underscores are usually reserved for use by the compiler.
ps -eo pid,etime,cmd|sort -n -k2
The usual error is one tries to put Content-Type: {multipart/form-data}
into the header of the post request. That will fail, it is best to let Postman do it for you. For example:
Unfortunatelly, today (September 2018) you can not find cross-browser solution for client side file writing.
For example: in some browser like a Chrome we have today this possibility and we can write with FileSystemFileEntry.createWriter() with client side call, but according to the docu:
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.
For IE (but not MS Edge) we could use ActiveX too, but this is only for this client.
If you want update your JSON file cross-browser you have to use server and client side together.
On client side you can make a request to the server and then you have to read the response from server. Or you could read a file with FileReader too. For the cross-browser writing to the file you have to have some server (see below on server part).
var xhr = new XMLHttpRequest(),
jsonArr,
method = "GET",
jsonRequestURL = "SOME_PATH/jsonFile/";
xhr.open(method, jsonRequestURL, true);
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
// we convert your JSON into JavaScript object
jsonArr = JSON.parse(xhr.responseText);
// we add new value:
jsonArr.push({"nissan": "sentra", "color": "green"});
// we send with new request the updated JSON file to the server:
xhr.open("POST", jsonRequestURL, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// if you want to handle the POST response write (in this case you do not need it):
// xhr.onreadystatechange = function(){ /* handle POST response */ };
xhr.send("jsonTxt="+JSON.stringify(jsonArr));
// but on this place you have to have a server for write updated JSON to the file
}
};
xhr.send(null);
You can use a lot of different servers, but I would like to write about PHP and Node.js servers.
By using searching machine you could find "free PHP Web Hosting*" or "free Node.js Web Hosting". For PHP server I would recommend 000webhost.com and for Node.js I would recommend to see and to read this list.
PHP server side script solution
The PHP script for reading and writing from JSON file:
<?php
// This PHP script must be in "SOME_PATH/jsonFile/index.php"
$file = 'jsonFile.txt';
if($_SERVER['REQUEST_METHOD'] === 'POST')
// or if(!empty($_POST))
{
file_put_contents($file, $_POST["jsonTxt"]);
//may be some error handeling if you want
}
else if($_SERVER['REQUEST_METHOD'] === 'GET')
// or else if(!empty($_GET))
{
echo file_get_contents($file);
//may be some error handeling if you want
}
?>
Node.js server side script solution
I think that Node.js is a little bit complex for beginner. This is not normal JavaScript like in browser. Before you start with Node.js I would recommend to read one from two books:
The Node.js script for reading and writing from JSON file:
var http = require("http"),
fs = require("fs"),
port = 8080,
pathToJSONFile = '/SOME_PATH/jsonFile.txt';
http.createServer(function(request, response)
{
if(request.method == 'GET')
{
response.writeHead(200, {"Content-Type": "application/json"});
response.write(fs.readFile(pathToJSONFile, 'utf8'));
response.end();
}
else if(request.method == 'POST')
{
var body = [];
request.on('data', function(chunk)
{
body.push(chunk);
});
request.on('end', function()
{
body = Buffer.concat(body).toString();
var myJSONdata = body.split("=")[1];
fs.writeFileSync(pathToJSONFile, myJSONdata); //default: 'utf8'
});
}
}).listen(port);
Related links for Node.js:
If you want to set an html content containg script tag to iframe, you have access to the iframe you created with:
$(iframeElement).contentWindow.document
so you can set innerHTML of any element in this.
But, for script tag, you should create and append an script tag, like this:
Ignoring the smooth interpolation between points in your example graph (that would require doing some manual interpolation, or just have a higher resolution of your data), you can use pyplot.fill_between()
:
from matplotlib import pyplot as plt
import numpy as np
x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape)
y += np.random.normal(0, 0.1, size=y.shape)
plt.plot(x, y, 'k-')
plt.fill_between(x, y-error, y+error)
plt.show()
See also the matplotlib examples.
At a very high level:
Abstraction of any kind comes down to separating concerns. "Client" code of an abstraction doesn't care how the contract exposed by the abstraction is fulfilled. You usually don't care if a string class uses a null-terminated or buffer-length-tracked internal storage implementation, for example. Encapsulation hides the details, but by making classes/methods/etc. abstract, you allow the implementation to change or for new implementations to be added without affecting the client code.
That is because you are opening , writing and closing the file 10 times inside your for loop
myfile = open('xyz.txt', 'w')
myfile.writelines(var1)
myfile.close()
You should open and close your file outside for loop.
myfile = open('xyz.txt', 'w')
for line in lines:
var1, var2 = line.split(",");
myfile.write("%s\n" % var1)
myfile.close()
text_file.close()
You should also notice to use write and not writelines.
writelines
writes a list of lines to your file.
Also you should check out the answers posted by folks here that uses with
statement. That is the elegant way to do file read/write operations in Python
You can enable this in Window - Preferences - General - Workspace - Refresh Automatically (called Refresh using native hooks or polling in newer builds)
The only reason I can think why this isn't enabled by default is performance related.
For example, refreshing source folders automatically might trigger a build of the workspace. Perhaps some people want more control over this.
There is also an article on the Eclipse site regarding auto refresh.
Basically, there is no external trigger that notifies Eclipse of files changed outside the workspace. Rather a background thread is used by Eclipse to monitor file changes that can possibly lead to performance issues with large workspaces.
I had this problem when I was using an undefined variable inside the with open(...) as f:
.
I removed (or I defined outside) the undefined variable and the problem disappeared.
You can directly return a different view like:
return View("NameOfView", Model);
Or you can make a partial view and can return like:
return PartialView("PartialViewName", Model);
The MaterialModule
was deprecated in the beta3 version with the goal that developers should only import into their applications what they are going to use and thus improve the bundle size.
The developers have now 2 options:
MyMaterialModule
which imports/exports the components that your application requires and can be imported by other (feature) modules in your application.Take the following as example (extracted from material page)
First approach:
import {MdButtonModule, MdCheckboxModule} from '@angular/material';
@NgModule({
imports: [MdButtonModule, MdCheckboxModule],
exports: [MdButtonModule, MdCheckboxModule],
})
export class MyOwnCustomMaterialModule { }
Then you can import this module into any of yours.
Second approach:
import {MdButtonModule, MdCheckboxModule} from '@angular/material';
@NgModule({
...
imports: [MdButtonModule, MdCheckboxModule],
...
})
export class PizzaPartyAppModule { }
Now you can use the respective material components in all the components declared in PizzaPartyAppModule
It is worth mentioning the following:
BrowserAnimationsModule
into your main module if you want the
animations to work@angular/cdk
to their package.json
(material dependency)BrowserModule
, as stated by the docs: Whichever approach you use, be sure to import the Angular Material modules after Angular's BrowserModule, as the import order matters for NgModules.
If you're willing to transmit some data and that you don't need to be secured (any public infos) you can use a CORS proxy, it's very easy, you'll not have to change anything in your code or in server side (especially of it's not your server like the Yahoo API or OpenWeather). I've used it to fetch JSON files with an XMLHttpRequest and it worked fine.
I would simplify comm1x's Kotlin extension function even more:
fun Bitmap.rotate(degrees: Float) =
Bitmap.createBitmap(this, 0, 0, width, height, Matrix().apply { postRotate(degrees) }, true)
It is simple. The first thing that you have to understand the design of the Python interpreter. It doesn't allocate memory for all the variables basically if any two or more variable has the same value it just map to that value.
let's go to the code example,
In [6]: a = 10
In [7]: id(a)
Out[7]: 10914656
In [8]: b = 10
In [9]: id(b)
Out[9]: 10914656
In [10]: c = 11
In [11]: id(c)
Out[11]: 10914688
In [12]: d = 21
In [13]: id(d)
Out[13]: 10915008
In [14]: e = 11
In [15]: id(e)
Out[15]: 10914688
In [16]: e = 21
In [17]: id(e)
Out[17]: 10915008
In [18]: e is d
Out[18]: True
In [19]: e = 30
In [20]: id(e)
Out[20]: 10915296
From the above output, variables a and b shares the same memory, c and d has different memory when I create a new variable e and store a value (11) which is already present in the variable c so it mapped to that memory location and doesn't create a new memory when I change the value present in the variable e to 21 which is already present in the variable d so now variables d and e share the same memory location. At last, I change the value in the variable e to 30 which is not stored in any other variable so it creates a new memory for e.
so any variable which is having same value shares the memory.
Not for list and dictionary objects
let's come to your question.
when multiple keys have same value then all shares same memory so the thing that you expect is already there in python.
you can simply use it like this
In [49]: dictionary = {
...: 'k1':1,
...: 'k2':1,
...: 'k3':2,
...: 'k4':2}
...:
...:
In [50]: id(dictionary['k1'])
Out[50]: 10914368
In [51]: id(dictionary['k2'])
Out[51]: 10914368
In [52]: id(dictionary['k3'])
Out[52]: 10914400
In [53]: id(dictionary['k4'])
Out[53]: 10914400
From the above output, the key k1 and k2 mapped to the same address which means value one stored only once in the memory which is multiple key single value dictionary this is the thing you want. :P
You can do this using the splat operator:
some_func(*params)
This causes the function to receive each list item as a separate parameter. There's a description here: http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists
If you don't want to install SMO objects you can use gplex tool (see this answer)
I know this was posted a long while ago, and it has been marked answered, but to me, the selected answer was not answering the question I thought the user was posing. It seemed to me he was looking for the approach one can take in ASP .Net that corresponds to his inline data binding previously performed in php.
Here was his php:
<p>Here is the username: <?php echo GetUserName(); ?></p>
Here is what one would do in ASP .Net:
<p>Here is the username: <%= GetUserName() %></p>
The easiest solution is to just run your own counter thus:
int i = 0;
for (String s : stringArray) {
doSomethingWith(s, i);
i++;
}
The reason for this is because there's no actual guarantee that items in a collection (which that variant of for
iterates over) even have an index, or even have a defined order (some collections may change the order when you add or remove elements).
See for example, the following code:
import java.util.*;
public class TestApp {
public static void AddAndDump(AbstractSet<String> set, String str) {
System.out.println("Adding [" + str + "]");
set.add(str);
int i = 0;
for(String s : set) {
System.out.println(" " + i + ": " + s);
i++;
}
}
public static void main(String[] args) {
AbstractSet<String> coll = new HashSet<String>();
AddAndDump(coll, "Hello");
AddAndDump(coll, "My");
AddAndDump(coll, "Name");
AddAndDump(coll, "Is");
AddAndDump(coll, "Pax");
}
}
When you run that, you can see something like:
Adding [Hello]
0: Hello
Adding [My]
0: Hello
1: My
Adding [Name]
0: Hello
1: My
2: Name
Adding [Is]
0: Hello
1: Is
2: My
3: Name
Adding [Pax]
0: Hello
1: Pax
2: Is
3: My
4: Name
indicating that, rightly so, order is not considered a salient feature of a set.
There are other ways to do it without a manual counter but it's a fair bit of work for dubious benefit.
No need to pass anything in. The function used for addEventListener
will automatically have this
bound to the current element. Simply use this
in your function:
productLineSelect.addEventListener('change', getSelection, false);
function getSelection() {
var value = this.options[this.selectedIndex].value;
alert(value);
}
Here's the fiddle: http://jsfiddle.net/dJ4Wm/
If you want to pass arbitrary data to the function, wrap it in your own anonymous function call:
productLineSelect.addEventListener('change', function() {
foo('bar');
}, false);
function foo(message) {
alert(message);
}
Here's the fiddle: http://jsfiddle.net/t4Gun/
If you want to set the value of this
manually, you can use the call
method to call the function:
var self = this;
productLineSelect.addEventListener('change', function() {
getSelection.call(self);
// This'll set the `this` value inside of `getSelection` to `self`
}, false);
function getSelection() {
var value = this.options[this.selectedIndex].value;
alert(value);
}
I was interested in this question, so I did a test just now. Using .NET Framework 4.5.2 on an Intel(R) Core(TM) i3-2328M CPU @ 2.20GHz, 2200 Mhz, 2 Core(s) with 8GB ram running Microsoft Windows 7 Ultimate.
It looks like LINQ might be faster than for each loop. Here are the results I got:
Exists = True
Time = 174
Exists = True
Time = 149
It would be interesting if some of you could copy & paste this code in a console app and test as well. Before testing with an object (Employee) I tried the same test with integers. LINQ was faster there as well.
public class Program
{
public class Employee
{
public int id;
public string name;
public string lastname;
public DateTime dateOfBirth;
public Employee(int id,string name,string lastname,DateTime dateOfBirth)
{
this.id = id;
this.name = name;
this.lastname = lastname;
this.dateOfBirth = dateOfBirth;
}
}
public static void Main() => StartObjTest();
#region object test
public static void StartObjTest()
{
List<Employee> items = new List<Employee>();
for (int i = 0; i < 10000000; i++)
{
items.Add(new Employee(i,"name" + i,"lastname" + i,DateTime.Today));
}
Test3(items, items.Count-100);
Test4(items, items.Count - 100);
Console.Read();
}
public static void Test3(List<Employee> items, int idToCheck)
{
Stopwatch s = new Stopwatch();
s.Start();
bool exists = false;
foreach (var item in items)
{
if (item.id == idToCheck)
{
exists = true;
break;
}
}
Console.WriteLine("Exists=" + exists);
Console.WriteLine("Time=" + s.ElapsedMilliseconds);
}
public static void Test4(List<Employee> items, int idToCheck)
{
Stopwatch s = new Stopwatch();
s.Start();
bool exists = items.Exists(e => e.id == idToCheck);
Console.WriteLine("Exists=" + exists);
Console.WriteLine("Time=" + s.ElapsedMilliseconds);
}
#endregion
#region int test
public static void StartIntTest()
{
List<int> items = new List<int>();
for (int i = 0; i < 10000000; i++)
{
items.Add(i);
}
Test1(items, -100);
Test2(items, -100);
Console.Read();
}
public static void Test1(List<int> items,int itemToCheck)
{
Stopwatch s = new Stopwatch();
s.Start();
bool exists = false;
foreach (var item in items)
{
if (item == itemToCheck)
{
exists = true;
break;
}
}
Console.WriteLine("Exists=" + exists);
Console.WriteLine("Time=" + s.ElapsedMilliseconds);
}
public static void Test2(List<int> items, int itemToCheck)
{
Stopwatch s = new Stopwatch();
s.Start();
bool exists = items.Contains(itemToCheck);
Console.WriteLine("Exists=" + exists);
Console.WriteLine("Time=" + s.ElapsedMilliseconds);
}
#endregion
}
Hopefully working code (didn't do much testing):
function toFixed(value, precision) {
var precision = precision || 0,
neg = value < 0,
power = Math.pow(10, precision),
value = Math.round(value * power),
integral = String((neg ? Math.ceil : Math.floor)(value / power)),
fraction = String((neg ? -value : value) % power),
padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0');
return precision ? integral + '.' + padding + fraction : integral;
}
Short answer is that you don't 'decrypt' the password (because it's not encrypted - it's hashed).
The long answer is that you shouldn't send the user their password by email, or any other way. If the user has forgotten their password, you should send them a password reset email, and allow them to change their password on your website.
Laravel has most of this functionality built in (see the Laravel documentation - I'm not going to replicate it all here. Also available for versions 4.2 and 5.0 of Laravel).
For further reading, check out this 'blogoverflow' post: Why passwords should be hashed.
This works for me, hope this will work for you too. It will give you a Record set Root to Child for any Specific Menu. Change the Field name as per your requirements.
SET @id:= '22';
SELECT Menu_Name, (@id:=Sub_Menu_ID ) as Sub_Menu_ID, Menu_ID
FROM
( SELECT Menu_ID, Menu_Name, Sub_Menu_ID
FROM menu
ORDER BY Sub_Menu_ID DESC
) AS aux_table
WHERE Menu_ID = @id
ORDER BY Sub_Menu_ID;
To sort by second field only (thus where second fields match, those lines with matches remain in the order they are in the original without sorting on other fields) :
sort -k 2,2 -s orig_file > sorted_file
if you are developing QGIS plugins then simply
self.dlg.cbo_load_net.currentIndex()
You can setup global parameter with
jQuery.ajaxSettings.traditional = true;
Replace(@"\""", "")
You have to use double-doublequotes to escape double-quotes within a verbatim string.
Use the astype
method.
>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x
array([[ 1. , 2.3],
[ 1.3, 2.9]])
>>> x.astype(int)
array([[1, 2],
[1, 2]])
Direct answer: No
But you can simulate reference with wrappers.
And do the following:
void changeString( _<String> str ) {
str.s("def");
}
void testRef() {
_<String> abc = new _<String>("abc");
changeString( abc );
out.println( abc ); // prints def
}
Out
void setString( _<String> ref ) {
str.s( "def" );
}
void testOut(){
_<String> abc = _<String>();
setString( abc );
out.println(abc); // prints def
}
And basically any other type such as:
_<Integer> one = new <Integer>(1);
addOneTo( one );
out.println( one ); // May print 2
You need to add the python executable path to your Window's PATH variable.
c:\Python27\
). Each different directory is separated with a
semicolon. (Note: do not put spaces between elements in the PATH
. Your addition to the PATH
should read ;c:\Python27
NOT ; C\Python27
)cmd.exe
should be sufficient.In order to kill use:
killall -9 /usr/bin/node
To reload use:
killall -12 /usr/bin/node
If you want update one line, but the information is too long to show on one line, it may need some new lines. I've encountered this problem, and below is one way to solve this.
public class DumpOutPutInforInSameLine
{
//content show in how many lines
int TotalLine = 0;
//start cursor line
int cursorTop = 0;
// use to set character number show in one line
int OneLineCharNum = 75;
public void DumpInformation(string content)
{
OutPutInSameLine(content);
SetBackSpace();
}
static void backspace(int n)
{
for (var i = 0; i < n; ++i)
Console.Write("\b \b");
}
public void SetBackSpace()
{
if (TotalLine == 0)
{
backspace(OneLineCharNum);
}
else
{
TotalLine--;
while (TotalLine >= 0)
{
backspace(OneLineCharNum);
TotalLine--;
if (TotalLine >= 0)
{
Console.SetCursorPosition(OneLineCharNum, cursorTop + TotalLine);
}
}
}
}
private void OutPutInSameLine(string content)
{
//Console.WriteLine(TotalNum);
cursorTop = Console.CursorTop;
TotalLine = content.Length / OneLineCharNum;
if (content.Length % OneLineCharNum > 0)
{
TotalLine++;
}
if (TotalLine == 0)
{
Console.Write("{0}", content);
return;
}
int i = 0;
while (i < TotalLine)
{
int cNum = i * OneLineCharNum;
if (i < TotalLine - 1)
{
Console.WriteLine("{0}", content.Substring(cNum, OneLineCharNum));
}
else
{
Console.Write("{0}", content.Substring(cNum, content.Length - cNum));
}
i++;
}
}
}
class Program
{
static void Main(string[] args)
{
DumpOutPutInforInSameLine outPutInSameLine = new DumpOutPutInforInSameLine();
outPutInSameLine.DumpInformation("");
outPutInSameLine.DumpInformation("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
outPutInSameLine.DumpInformation("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
outPutInSameLine.DumpInformation("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
//need several lines
outPutInSameLine.DumpInformation("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
outPutInSameLine.DumpInformation("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
outPutInSameLine.DumpInformation("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
outPutInSameLine.DumpInformation("bbbbbbbbbbbbbbbbbbbbbbbbbbb");
}
}
Use the RAISERROR
function:
RAISERROR( 'This message will show up right away...',0,1) WITH NOWAIT
You shouldn't completely replace all your prints with raiserror. If you have a loop or large cursor somewhere just do it once or twice per iteration or even just every several iterations.
Also: I first learned about RAISERROR at this link, which I now consider the definitive source on SQL Server Error handling and definitely worth a read:
http://www.sommarskog.se/error-handling-I.html
You have two options,
-If you want the value:
Dim MyValue as Variant ' or string/date/long/...
MyValue = ThisWorkbook.Sheets(1).Range("A1").Value
-if you want the cell object:
Dim oCell as Range ' or object (but then you'll miss out on intellisense), and both can also contain more than one cell.
Set oCell = ThisWorkbook.Sheets(1).Range("A1")
Update: The site below is no longer running because, as they say on the site:
As of January 1, 2016, no publicly trusted CA is allowed to issue a SHA-1 certificate. In addition, SHA-1 support was removed by most modern browsers and operating systems in early 2017. Any new certificate you get should automatically use a SHA-2 algorithm for its signature.
Legacy clients will continue to accept SHA-1 certificates, and it is possible to have requested a certificate on December 31, 2015 that is valid for 39 months. So, it is possible to see SHA-1 certificates in the wild that expire in early 2019.
You can also use https://shaaaaaaaaaaaaa.com/ - set up to make this particular task easy. The site has a text box - you type in your site domain name, click the Go button and it then tells you whether the site is using SHA1 or SHA2.
InetAddress.getLocalHost().getHostName()
is better (as explained by Nick), but still not very good
One host can be known under many different hostnames. Usually you'll be looking for the hostname your host has in a specific context.
For example, in a web application, you might be looking for the hostname used by whoever issued the request you're currently handling. How to best find that one depends on which framework you're using for your web application.
In some kind of other internet-facing service, you'll want the hostname your service is available through from the 'outside'. Due to proxies, firewalls etc this might not even be a hostname on the machine your service is installed on - you might try to come up with a reasonable default, but you should definitely make this configurable for whoever installs this.
You are certainly overwriting your stack, but the program is simple enough that effects of this go unnoticed.
Here are the timeit results for the top 2 answers. Note that "file.txt" is a text file containing 100,000+ lines of random string with a file size of 1MB+.
Using itertools:
import itertools
from timeit import timeit
timeit("""with open("file.txt", "r") as fo:
for line in itertools.islice(fo, 90000, None):
line.strip()""", number=100)
>>> 1.604976346003241
Using two for loops:
from timeit import timeit
timeit("""with open("file.txt", "r") as fo:
for i in range(90000):
next(fo)
for j in fo:
j.strip()""", number=100)
>>> 2.427317383000627
clearly the itertools method is more efficient when dealing with large files.
The MOD
keyword only exists in the DAX
language (tabular dimensional queries), not TSQL
Use %
instead.
Ref: Modulo
To display current directory's files and subdirectories sizes recursively:
du -h .
To display the same size information but without printing their sub directories recursively (which can be a huge list), just use the --max-depth option:
du -h --max-depth=1 .
You can do something like this :
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" OnClientClick="document.forms[0].target = '_blank';" />
Here is code for image encoding and image decoding.
In an XML file
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yyuyuyuuyuyuyu"
android:id="@+id/tv5"
/>
In a Java file:
TextView textView5;
Bitmap bitmap;
textView5 = (TextView) findViewById(R.id.tv5);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... voids) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] byteFormat = stream.toByteArray();
// Get the Base64 string
String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
return imgString;
}
@Override
protected void onPostExecute(String s) {
textView5.setText(s);
}
}.execute();
Use div
instead of span
, or add display: block;
to your css style for the span
tag.
If your application theme is AppTheme(or anything else), then in styles.xml add the following code:
<style name="HiddenTitleTheme" parent="AppTheme">
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
</style>
Then in manifest file add the following in the activity tag for which you want to disable activity label:
android:theme="@style/HiddenTitleTheme"
The powershell script solution:
Based on the information in the answer from @kayleeFrye_onDeck
I have created a powershell script that checks and installs the versions the user specifies, i haven't done extensive testing with it, but for my own CI (Continuous Integration) scenario it work perfectly.
The full script and info on github
The approach i used was based on checking the regkeys based on information provided here. The following is the gist of what the script does:
function Test-RegistryValue {
param (
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]$Path,
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]$Value
)
try {
Get-ItemProperty -Path "$($Path+$Value)" -ErrorAction Stop | Out-Null
return $true
}
catch {
return $false
}
}
The checking/downloading/silently installing based on $redistInfo
which contains the compiled information from kayleeFrye_onDeck's.
$redistInstalled = Test-RegistryValue -Path $redistInfo.RegPath -Value $redistInfo.RegValue
if($redistInstalled -eq $False) {
Invoke-WebRequest -Uri $redistInfo.DownloadUrl -OutFile $downloadTargetPath
Start-Process -FilePath $downloadTargetPath -ArgumentList "$($redistInfo.SilentInstallArgs)" -Wait -NoNewWindow | Wait-Process
}
The full script and more information can be found on github
Anyone is welcome to contribute, if i have time i will do more extensive testing of the script and keep trying to add new packages as information is added here.
In general, this is not possible. In a branch history a branch-and-merge before a named branch was branched off and an intermediate branch of two named branches look the same.
In git, branches are just the current names of the tips of sections of history. They don't really have a strong identity.
This isn't usually a big issue as the merge-base (see Greg Hewgill's answer) of two commits is usually much more useful, giving the most recent commit which the two branches shared.
A solution relying on the order of parents of a commit obviously won't work in situations where a branch has been fully integrated at some point in the branch's history.
git commit --allow-empty -m root # actual branch commit
git checkout -b branch_A
git commit --allow-empty -m "branch_A commit"
git checkout master
git commit --allow-empty -m "More work on master"
git merge -m "Merge branch_A into master" branch_A # identified as branch point
git checkout branch_A
git merge --ff-only master
git commit --allow-empty -m "More work on branch_A"
git checkout master
git commit --allow-empty -m "More work on master"
This technique also falls down if an integration merge has been made with the parents reversed (e.g. a temporary branch was used to perform a test merge into master and then fast-forwarded into the feature branch to build on further).
git commit --allow-empty -m root # actual branch point
git checkout -b branch_A
git commit --allow-empty -m "branch_A commit"
git checkout master
git commit --allow-empty -m "More work on master"
git merge -m "Merge branch_A into master" branch_A # identified as branch point
git checkout branch_A
git commit --allow-empty -m "More work on branch_A"
git checkout -b tmp-branch master
git merge -m "Merge branch_A into tmp-branch (master copy)" branch_A
git checkout branch_A
git merge --ff-only tmp-branch
git branch -d tmp-branch
git checkout master
git commit --allow-empty -m "More work on master"
TL;DR) See this table: https://www.tensorflow.org/install/source#gpu
Check the CUDA version:
cat /usr/local/cuda/version.txt
and cuDNN version:
grep CUDNN_MAJOR -A 2 /usr/local/cuda/include/cudnn.h
and install a combination as given below in the images or here.
The following images and the link provide an overview of the officially supported/tested combinations of CUDA and TensorFlow on Linux, macOS and Windows:
Since the given specifications below in some cases might be too broad, here is one specific configuration that works:
tensorflow-gpu==1.12.0
cuda==9.0
cuDNN==7.1.4
The corresponding cudnn can be downloaded here.
Please refer to https://www.tensorflow.org/install/source#gpu for a up-to-date compatibility chart (for official TF wheels).
(figures updated May 20, 2020)
Updated as of Dec 5 2020: For the updated information please refer Link for Linux and Link for Windows.
DEMO
In the content area you can provide whatever you want to display in it.
.black_overlay {_x000D_
display: none;_x000D_
position: absolute;_x000D_
top: 0%;_x000D_
left: 0%;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background-color: black;_x000D_
z-index: 1001;_x000D_
-moz-opacity: 0.8;_x000D_
opacity: .80;_x000D_
filter: alpha(opacity=80);_x000D_
}_x000D_
.white_content {_x000D_
display: none;_x000D_
position: absolute;_x000D_
top: 25%;_x000D_
left: 25%;_x000D_
width: 50%;_x000D_
height: 50%;_x000D_
padding: 16px;_x000D_
border: 16px solid orange;_x000D_
background-color: white;_x000D_
z-index: 1002;_x000D_
overflow: auto;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>LIGHTBOX EXAMPLE</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<p>This is the main content. To display a lightbox click <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a>_x000D_
</p>_x000D_
<div id="light" class="white_content">This is the lightbox content. <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a>_x000D_
</div>_x000D_
<div id="fade" class="black_overlay"></div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
You need to open the connection first:
SQLConnection.Open();
Try dir /b
, for bare format.
dir /?
will show you documentation of what you can do with the dir
command. Here is the output from my Windows 7 machine:
C:\>dir /?
Displays a list of files and subdirectories in a directory.
DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
[/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]
[drive:][path][filename]
Specifies drive, directory, and/or files to list.
/A Displays files with specified attributes.
attributes D Directories R Read-only files
H Hidden files A Files ready for archiving
S System files I Not content indexed files
L Reparse Points - Prefix meaning not
/B Uses bare format (no heading information or summary).
/C Display the thousand separator in file sizes. This is the
default. Use /-C to disable display of separator.
/D Same as wide but files are list sorted by column.
/L Uses lowercase.
/N New long list format where filenames are on the far right.
/O List by files in sorted order.
sortorder N By name (alphabetic) S By size (smallest first)
E By extension (alphabetic) D By date/time (oldest first)
G Group directories first - Prefix to reverse order
/P Pauses after each screenful of information.
/Q Display the owner of the file.
/R Display alternate data streams of the file.
/S Displays files in specified directory and all subdirectories.
/T Controls which time field displayed or used for sorting
timefield C Creation
A Last Access
W Last Written
/W Uses wide list format.
/X This displays the short names generated for non-8dot3 file
names. The format is that of /N with the short name inserted
before the long name. If no short name is present, blanks are
displayed in its place.
/4 Displays four-digit years
Switches may be preset in the DIRCMD environment variable. Override
preset switches by prefixing any switch with - (hyphen)--for example, /-W.
When TypeScript thinks that property "x" does not exist on "y", then you can always cast "y" into "any", which will allow you to call anything (like "x") on "y".
Theory
(<any>y).x;
Real World Example
I was getting the error "TS2339: Property 'name' does not exist on type 'Function'" for this code:
let name: string = this.constructor.name;
So I fixed it with:
let name: string = (<any>this).constructor.name;
1. About onCreate() and onUpgrade()
onCreate(..)
is called whenever the app is freshly installed. onUpgrade
is called whenever the app is upgraded and launched and the database version is not the same.
2. Incrementing the db version
You need a constructor like:
MyOpenHelper(Context context) {
super(context, "dbname", null, 2); // 2 is the database version
}
IMPORTANT: Incrementing the app version alone is not enough for onUpgrade
to be called!
3. Don't forget your new users!
Don't forget to add
database.execSQL(DATABASE_CREATE_color);
to your onCreate() method as well or newly installed apps will lack the table.
4. How to deal with multiple database changes over time
When you have successive app upgrades, several of which have database upgrades, you want to be sure to check oldVersion
:
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch(oldVersion) {
case 1:
db.execSQL(DATABASE_CREATE_color);
// we want both updates, so no break statement here...
case 2:
db.execSQL(DATABASE_CREATE_someothertable);
}
}
This way when a user upgrades from version 1 to version 3, they get both updates. When a user upgrades from version 2 to 3, they just get the revision 3 update... After all, you can't count on 100% of your user base to upgrade each time you release an update. Sometimes they skip an update or 12 :)
5. Keeping your revision numbers under control while developing
And finally... calling
adb uninstall <yourpackagename>
totally uninstalls the app. When you install again, you are guaranteed to hit onCreate
which keeps you from having to keep incrementing the database version into the stratosphere as you develop...
Try:
require(Hmisc)
sapply(name, function(x) {
paste(sapply(strsplit(x, ' '), capitalize), collapse=' ')
})
You can also use jQuery('.class-name').attr("href")
, in my case it works better.
Here more information: "jQuery(...)" instead of "$(...)"
I'm posting this late answer primarily because Google likes this question.
I believe the issue and context really should be about the workflow, not the tools. The overall philosophy is always "Use the right tool for the job." But before this comes one that many often forget when they get lost in the tools: "Get the job done."
When I have a problem that isn't completely defined, I almost always start with Bash. I have solved some gnarly problems in large Bash scripts that are both readable and maintainable.
But when does the problem start to exceed what Bash should be asked to do? I have some checks I use to give me warnings:
The list goes on. Bottom-line, when you are working harder to keep your scripts running that you do adding features, it's time to leave Bash.
Let's assume you've decided to move your work to Python. If your Bash scripts are clean, the initial conversion is quite straightforward. There are even several converters / translators that will do the first pass for you.
The next question is: What do you give up moving to Python?
All calls to external utilities must be wrapped in something from the subprocess
module (or equivalent). There are multiple ways to do this, and until 3.7 it took some effort to get it right (3.7 improved subprocess.run()
to handle all common cases on its own).
Surprisingly, Python has no standard platform-independent non-blocking utility (with timeout) for polling the keyboard (stdin). The Bash read
command is an awesome tool for simple user interaction. My most common use is to show a spinner until the user presses a key, while also running a polling function (with each spinner step) to make sure things are still running well. This is a harder problem than it would appear at first, so I often simply make a call to Bash: Expensive, but it does precisely what I need.
If you are developing on an embedded or memory-constrained system, Python's memory footprint can be many times larger than Bash's (depending on the task at hand). Plus, there is almost always an instance of Bash already in memory, which may not be the case for Python.
For scripts that run once and exit quickly, Python's startup time can be much longer than Bash's. But if the script contains significant calculations, Python quickly pulls ahead.
Python has the most comprehensive package system on the planet. When Bash gets even slightly complex, Python probably has a package that makes whole chunks of Bash become a single call. However, finding the right package(s) to use is the biggest and most daunting part of becoming a Pythonista. Fortunately, Google and StackExchange are your friends.
Compile with O3, The compiler performs optimization well.
q = x / y;
if (x % y) ++q;
You don't need to use an indexer (since it a bit less typesafe). You have two options :
interface EnumServiceItem {
id: number; label: string; key: any
}
interface EnumServiceItems extends Array<EnumServiceItem>{}
// Option A
var result: EnumServiceItem[] = [
{ id: 0, label: 'CId', key: 'contentId' },
{ id: 1, label: 'Modified By', key: 'modifiedBy' },
{ id: 2, label: 'Modified Date', key: 'modified' },
{ id: 3, label: 'Status', key: 'contentStatusId' },
{ id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
{ id: 5, label: 'Title', key: 'title' },
{ id: 6, label: 'Type', key: 'contentTypeId' },
{ id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] }
];
// Option B
var result: EnumServiceItems = [
{ id: 0, label: 'CId', key: 'contentId' },
{ id: 1, label: 'Modified By', key: 'modifiedBy' },
{ id: 2, label: 'Modified Date', key: 'modified' },
{ id: 3, label: 'Status', key: 'contentStatusId' },
{ id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
{ id: 5, label: 'Title', key: 'title' },
{ id: 6, label: 'Type', key: 'contentTypeId' },
{ id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] }
]
Personally I recommend Option A (simpler migration when you are using classes not interfaces).
You could translate spaces to newlines and then grep, e.g.:
cat * | tr ' ' '\n' | grep th